mongodb move documents to another collection

Solutions on MaxInterview for mongodb move documents to another collection by the best coders in the world

showing results for - "mongodb move documents to another collection"
Maria
26 Sep 2017
1function insertBatch(collection, documents) {
2  var bulkInsert = collection.initializeUnorderedBulkOp();
3  var insertedIds = [];
4  var id;
5  documents.forEach(function(doc) {
6    id = doc._id;
7    // Insert without raising an error for duplicates
8    bulkInsert.find({_id: id}).upsert().replaceOne(doc);
9    insertedIds.push(id);
10  });
11  bulkInsert.execute();
12  return insertedIds;
13}
14
15function deleteBatch(collection, documents) {
16  var bulkRemove = collection.initializeUnorderedBulkOp();
17  documents.forEach(function(doc) {
18    bulkRemove.find({_id: doc._id}).removeOne();
19  });
20  bulkRemove.execute();
21}
22
23function moveDocuments(sourceCollection, targetCollection, filter, batchSize) {
24  print("Moving " + sourceCollection.find(filter).count() + " documents from " + sourceCollection + " to " + targetCollection);
25  var count;
26  while ((count = sourceCollection.find(filter).count()) > 0) {
27    print(count + " documents remaining");
28    sourceDocs = sourceCollection.find(filter).limit(batchSize);
29    idsOfCopiedDocs = insertBatch(targetCollection, sourceDocs);
30
31    targetDocs = targetCollection.find({_id: {$in: idsOfCopiedDocs}});
32    deleteBatch(sourceCollection, targetDocs);
33  }
34  print("Done!")
35}