Duplicate a document in MongoDB using a new _id
Ok, I suppose that this is a silly question and probably has a simple answer.
How can I duplicate a document in MongoDB, changing the _id of the new one?
Imaging that you have the original document:
> var orig = db.MyCollection.findOne({_id: 'hi'})
And now I want another document in the collection with _id 'bye'.
Just change the id and re-insert.
> db.coll.insert({_id: 'hi', val: 1})
> var orig = db.coll.findOne({_id: 'hi'})
> orig._id = 'bye'
bye
> db.coll.insert(orig)
> db.coll.find()
{ "_id" : "hi", "val" : 1 }
{ "_id" : "bye", "val" : 1 }
You can give a new ObjectId to the copy Document. In mongo shell
var copy = db.collection.findOne();
for (var i = 0; i< 30; i++){
copy._id = new ObjectId();
db.collection.insert(copy);
}