Skip to content

Instantly share code, notes, and snippets.

@guyellis
Created April 3, 2014 04:17
Show Gist options
  • Save guyellis/9948194 to your computer and use it in GitHub Desktop.
Save guyellis/9948194 to your computer and use it in GitHub Desktop.
How to duplicate the records in a MongoDB collection
// Fill out a literal array of collections you want to duplicate the records in.
// Iterate over each collection using the forEach method on the array.
// For each collection get (find) all the records and forEach on each of them.
// Remove the _id field from each record as MongoDB will generate this for you and
// you can't have a duplicate.
// Save the record.
// This assumes that the collection does not have any unique keys set on any of the
// other fields.
// Run this in the MongoDB shell
[db.<collection1>, db.<collection2>].forEach(function(collection)
{
collection.find({}).forEach(function(x) {
delete x._id;
collection.save(x);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment