Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate a document in MongoDB using a new _id

Tags:

mongodb

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'.

like image 754
José María Ruiz Avatar asked Aug 01 '12 16:08

José María Ruiz


People also ask

How do I duplicate a document in MongoDB?

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.

Can we replace _ID in MongoDB?

You cannot update it. You'll have to save the document using a new _id , and then remove the old document.

What is _ID in MongoDB?

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.


2 Answers

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 } 
like image 99
Sergio Tulentsev Avatar answered Sep 18 '22 22:09

Sergio Tulentsev


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); } 
like image 40
689 Avatar answered Sep 17 '22 22:09

689