How do you clone ( duplicate ) a MongoDB object in a collection of the same db? How do you clone ( duplicate ) a MongoDB object in a collection of the same db? database database

How do you clone ( duplicate ) a MongoDB object in a collection of the same db?


Code

> user = db.users.findOne({'nickname': 'user1'})> user.nickname = 'userX'> delete user['_id']> db.users.insert(user)

Description

You need to find user object and put it into the variable. Than you need to modify the property you want and than you need to insert the whole object as new one. To achieve that you need to delete _id property that the object already has. And than just use insert to create the new one.


Do not delete the _id property; for some reason some values lose their type. For example, integers are converted to doubles.

Use this solution:

var user = db.users.findOne(...)user._id = new ObjectId()// set other propertiesdb.users.insert(user)


The _id field is a required field and we can't delete it like that. What I do is call toJSON() to the returned object and then delete the _id.

var rObject = dbObject.toJSON();delete rObject._id;db.insert(rObject);