I have got mongo db called test
and in this db two collections collection1
and collection1_backup
.
How to replace content of collection1
with data from collection1_backup
.
8 Answers
The best way to have done this (considering the name of the collection ends with _backup
) is possibly to have used mongorestore: http://docs.mongodb.org/manual/reference/mongorestore/
However in this case it depends. If the collection is unsharded you can use renameCollection
( http://docs.mongodb.org/manual/reference/command/renameCollection/ ) or you can use a more manual method of (in JavaScript code):
db.collection1.drop(); // Drop entire other collection
db.collection1_backup.find().forEach(function(doc){
db.collection1.insert(doc); // start to replace
});
Those are the most common methods of doing this.
-
2
-
@DenisDenisov have you got any proof of that? I would imagine that the two (manual method and aggregation framework, this method would definitely not be faster than the copy function that's actually specifically designed to copy tables, though it might be considering the safety measures it might take) would copy relatively the same, they would need to read all rows into active working set and then save them back down, I don't really see how the aggregation framework would be faster, not to mention that it isn't really designed for such a thing– SammayeMay 14, 2020 at 9:10
-
Yes, I've just checked on a large collection. Collection and indexes use
wiredTiger.configString='block_compressor=zstd'
. Aggregation was almost instantly executed bypercona-server-mongodb-server-4.2.6-6.el7.x86_64
. May 14, 2020 at 9:17 -
@DenisDenisov instnatly? Even on a collection of 2m records another user records about 3 minutes stackoverflow.com/a/37870870/383478 and instantly is faster than the disk can actually write, so that defies the laws of science– SammayeMay 14, 2020 at 9:29
-
1Anyway,
db.collection1_backup.aggregate([ { $match: {} }, { $out: "collection1" } ])
works faster that.find().forEach(..insert
=~100rec/s forums.meteor.com/t/… mongobooster.useresponse.com/topic/… stackoverflow.com/questions/31466623/… May 15, 2020 at 13:34
This can be done using simple command:
db.collection1_backup.aggregate([ { $match: {} }, { $out: "collection1" } ])
This command will remove all the documents of collection1 and then make a clone of collection1_backup in collection1.
Generic Command would be
db.<SOURCE_COLLECTION>.aggregate([ { $match: {} }, { $out: "<TARGET_COLLECTION>" } ])
If TARGET_COLLECTION does not exist, the above command will create it.
also usefull: to export collection to json file
mongoexport --collection collection1_backup --out collection1.json
to import collection from json file
mongoimport --db test --collection collection1 --file collection1.json
to import single collection from backup/dump file one need to convert *.bson file to *.json by using
bsondump collection1_backup.bson > collection1_backup.json
-
10In general it is preferable to use
mongodump
andmongorestore
when copying collections, as converting documents to JSON and back may affect the data type fidelity. There are some data types that exist in BSON that can have a different representation in JSON where there is no strict JSON equivalent. Use ofmongoimport
/mongoexport
may be OK depending on your data, but this is an important caveat to be aware of.– StennieDec 18, 2012 at 11:03 -
@Stennie It's also important to note that doing a mongodump / mongorestore will preserve indexes. So, if you're trying to duplicate docs between collections, you won't be able to restore. mongoexport and mongoimport should be used if you're trying to duplicate docs between collections.– ivandovSep 8, 2017 at 15:18
-
1@ivandov You can skip recreating indexes (aside from the required
_id
index) withmongorestore --noIndexRestore
. Note thatmongorestore
(as at MongoDB 3.4) only does inserts; if a document with the same_id
exists, it will not be updated or replaced. Themongoimport
tool supports upserts (and in 3.4, merges), but works with text formats rather than MongoDB's native BSON format.mongodump
andmongorestore
are still the recommended options if you want to recreate data (and optionally, collection metadata) identically between MongoDB deployments.– StennieSep 8, 2017 at 23:44
simply just do this.
//drop collection1
db.collection1.drop();
//copy data from collection1_backup to collection1
db.collection1.insert(db.collection1_backup.find({},{_id:0}).toArray());
Better way would be to use .toArray()
db.collection1.drop(); // Drop entire other collection
// creates an array which can be accessed from "data"
db.collection1_backup.find().toArray(function(err, data) {
// creates a collection and inserting the array at once
db.collection1.insert(data);
});
-
1What about size optimization? If my collection is 2GB should I have 2GB RAM?– AmantelApr 4, 2018 at 12:51
You can use a simple command to Backup MongoDB Collection. It will work only on MongoDB 4.0 or earlier versions.
db.sourceCollectionName.copyTo('targetCollectionName')
Your targetCollectionName must be in Single(') or Double(") Quote
Note:
The db.collection.copyTo() method uses the eval command internally. As a result, the db.collection.copyTo() operation takes a global lock that blocks all other read and write operations until the db.collection.copyTo() completes.
-
copyTo
may require some special permissions and may also alter data when converting from BSON to JSON. Apr 5, 2019 at 9:43 -
copyTo was deprecated: docs.mongodb.com/manual/reference/method/db.collection.copyTo. Quote: "Starting in version 4.2, MongoDB removes the eval command. The deprecated db.collection.copyTo(), which wraps the eval command, can only be run against MongoDB 4.0 or earlier versions. For behavior and example, refer to the 4.0 or earlier version of the manual." Jul 8, 2020 at 20:33
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<DBObject> list = dbCursor.toArray();
DBCollection destination = database.getCollection(destinationCollection);
destination.insert(list, WriteConcern.NORMAL); //WRITE CONCERN is based on your requirment.
}
Drop collection1
then use this query
var cursor = db.collection1_backup.find();
var data = [];
while(cursor.hasNest()){
data.push(cursor.next());
}
db.collection1.insertMany(data)