mongo copy from one collection to another (on the same db)

后端 未结 7 609
暖寄归人
暖寄归人 2020-12-24 08:02

I have got mongo db called test and in this db two collections collection1 and collection1_backup. How to replace content of col

7条回答
  •  余生分开走
    2020-12-24 08:19

    Using Java Driver

    Try below one:

    public void copyTo(String db,String sourceCollection,String destinationCollection,int limit) throws        
    UnknownHostException {
    
        MongoClient mongo = new MongoClient("localhost", 27017);
        DB database = mongo.getDB(db);
        DBCollection collection = database.getCollection(sourceCollection);
        DBCursor dbCursor = collection.find().limit(limit);
        List list =  dbCursor.toArray();
        DBCollection destination =  database.getCollection(destinationCollection);
        destination.insert(list, WriteConcern.NORMAL); //WRITE CONCERN is based on your requirment.
    
    }
    

提交回复
热议问题