user5116395
user5116395

Reputation:

MongoDB updating by inserting new row

This works:

 db.users.update( { _id:ObjectId("1234")}, { $set: { active: 1 } } )

because:

If the field does not exist, $set will add a new field with the specified value, provided that the new field does not violate a type constraint.

So active is created with value "1" and I'm happy, because that's what I wanted.

But

 db.users.update( { _id:ObjectId("1234")},  { $set: { profile: { active: 1 } } } )

This, instead of writing "active:1" as a new row inside profile, will erase all the data of "profile" and then, when 'profile' is empty, finally insert "active:1". I just lost the data of 25k users (profile.name,profile.age, etc). Could someone explain why?

Upvotes: 0

Views: 963

Answers (2)

sahil gupta
sahil gupta

Reputation: 2349

The problem with your code is that when you did

db.users.update( { _id:ObjectId("1234")},  { $set: { profile: { active: 1 } } } )

It will update the value of profile field in the user collection, by replacing the content of profile field with { active: 1 } as the behaviour you got.

To update a particular field('active' in this case)in a particulardocument({ profile: { active: 1 } in this case)you have to use thedot notation. For example:

db.users.update( { _id:ObjectId("1234")},  { $set: { "profile.active": 1 } } )

It will also do an update, but now it will update the active field of the profile document in the usercollection.

Explaination

The $set operator replaces the value of a field with the specified value.

If the field does not exist, $set will add a new field with the specified value, provided that the new field does not violate a type constraint. If you specify a dotted path for a non-existent field, $set will create the embedded documents as needed to fulfill the dotted path to the field.

If you specify multiple field-value pairs, $set will update or create each field.

For ref: "http://docs.mongodb.org/manual/reference/operator/update/set/"

Upvotes: 0

Alexander Korzhykov
Alexander Korzhykov

Reputation: 1073

The $set operator replaces the value of a field with the specified value.

To update an embedded field, use the dot notation. When using the dot notation, enclose the whole dotted field name in quotes:

db.users.update( { _id:ObjectId("1234")},  { $set: { "profile.activeactive": 1 } } )

Upvotes: 1

Related Questions