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'.
To clone a document, hover over the desired document and click the Clone button. When you click the Clone button, Compass opens the document insertion dialog with the same schema and values as the cloned document. You can edit any of these fields and values before you insert the new document.
You cannot update it. You'll have to save the document using a new _id , and then remove the old document.
What Is MongoDB ObjectID? As MongoDB documentation explains, "ObjectIds are small, likely unique, fast to generate, and ordered." The _id field is a 12-byte Field of BSON type made up of several 2-4 byte chains and is the unique identifier/naming convention MongoDB uses across all its content.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With