Duplicate a document in MongoDB using a new _id

Mongodb

Mongodb Problem Overview


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

Mongodb Solutions


Solution 1 - Mongodb

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 }

Solution 2 - Mongodb

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);
}

Solution 3 - Mongodb

A little improvement to the @689 response

var copy = db.collection.findOne({},{_id:0});
for (var i = 0; i< 30; i++){ 
    db.collection.insert(copy);
}

Solution 4 - Mongodb

You can use below code :

Run using single line :

db.collectionName.find({"_id" : ObjectId("5a4e47e0a21698d455000009")}).forEach(function(doc){var newDoc = doc; delete newDoc._id; db.collectionName.insert(newDoc); })

a structural format for understanding :

db.collectionName.find({"_id" : ObjectId("5a4e47e0a21698d455000009")}).forEach(function(doc){
	var newDoc = doc;
	delete newDoc._id;
	db.collectionName.insert(newDoc);
})

Solution 5 - Mongodb

In mongo shell: It's OK

db.products.find().forEach( function(doc){db.products.insert(
{
	"price":doc.price,
	"name":doc.name,
	"typeName":doc.typeName,
	"image":doc.image
}
)} );

Solution 6 - Mongodb

single line

(function(doc){delete doc._id; db.collection.insert(doc)})(db.collection.findOne({ _id: ObjectId("60c9a684c7d51907c35ad463")}))

structured

(function(doc) {
  delete doc._id;
  db.collection.insert(doc);
})(db.collection.findOne({ _id: ObjectId('60c9a684c7d51907c35ad463') }));

// (function(doc){...})(doc)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJos&#233; Mar&#237;a RuizView Question on Stackoverflow
Solution 1 - MongodbSergio TulentsevView Answer on Stackoverflow
Solution 2 - Mongodb689View Answer on Stackoverflow
Solution 3 - MongodbpykissView Answer on Stackoverflow
Solution 4 - MongodbIrshad KhanView Answer on Stackoverflow
Solution 5 - MongodbTính Ngô QuangView Answer on Stackoverflow
Solution 6 - MongodbAlexView Answer on Stackoverflow