Often you may want to clone an existing collection for testing without modifying the original data. Let's look at how to easily clone a collection using a MongoDB script.
For the clone test, create an inventory and insert some sample data.
db.inventory.insertMany([
{item: "journal", qty: 25, tags: ["blank", "red"], size: {h: 14, w: 21, uom: "cm"}},
{item: "mat", qty: 85, tags: ["gray"], size: {h: 27.9, w: 35.5, uom: "cm"}},
{item: "mousepad", qty: 25, tags: ["gel", "blue"], size: {h: 19, w: 22.85, uom: "cm"}}
])
1.db.collection.find().forEach()
find().forEach() iterates over the collection's documents one by one with forEach and inserts them into another collection, inventory2. Since it processes documents one at a time, it has the drawback of being slow.
db.inventory.find().forEach(
function(docs){
db.inventory2.insert(docs);
})
2.db.collection.aggregate()
Using the $out operator of aggregate allows you to clone a bit faster.
Syntax
{ $out: { db: "<output-db>", coll: "<output-collection>" } }
db.inventory.aggregate([{ $match: {} }, { $out: "inventory3" }])