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 ?
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 properties
db.users.insert(user)
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