Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need to duplicate (clone) an object in the collection via dbshell. Having something like this :

> db.users.distinct( 'nickname' )
[
        "user1",
        "user2",
        "user3",
        "user4"
]
>

where user1 select a complex object in users collection, how can I duplicate the object then change (rename) user1 field in userX ?

like image 302
Luca G. Soave Avatar asked Mar 24 '12 10:03

Luca G. Soave


2 Answers

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.

like image 191
lig Avatar answered Oct 17 '22 00:10

lig


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 properties
db.users.insert(user)
like image 41
Ferran Maylinch Avatar answered Oct 17 '22 01:10

Ferran Maylinch