nickponline
nickponline

Reputation: 25914

What does $set do in MongoDB?

I can't see the difference between using it:

update({"name" : "nick"}, {"$set" : {"age" : 50}})

and not using it;

update({"name" : "nick"}, {"age" : 50})

from the example in documentation. It's not clear to me.

Thanks for the comment but if I use {"$set" : {"array_field" : [{'f' : 'v'}] }} it adds {'f' : 'v'} to the array instead of replacing the array with [{'f' : 'v'}], so why doesn't $set replace the array with the new one?

Upvotes: 3

Views: 334

Answers (2)

Sammaye
Sammaye

Reputation: 43884

This is working for me as expected:

> db.test.insert({"a":1, "b": [{"v":1, "b":1}]})
> db.test.find()
{ "_id" : ObjectId("5102c75c8e48734ea1220a9c"), "a" : 1, "b" : [ { "v" : 1, "b" : 1 } ] }
> db.test.update({"_id" : ObjectId("5102c75c8e48734ea1220a9c")}, {$set: {"b": [{"v":1}]}})
> db.test.find()
{ "_id" : ObjectId("5102c75c8e48734ea1220a9c"), "a" : 1, "b" : [ { "v" : 1 } ] }

I thought it could have been the way JS interpreted the array but it isn't, it works just dandy for me.

Can you show us the queries you are performing? Maybe a full script can replicate this behaviour?

Edit

I noticed your data was different so I have replicated it exactly below:

> db.test.insert({"a":1, "b": [{'f':'v'}]})
> db.test.find()
{ "_id" : ObjectId("5102c8868e48734ea1220a9d"), "a" : 1, "b" : [ { "f" : "v" } ] }
> db.test.update({ "_id" : ObjectId("5102c8868e48734ea1220a9d")}, {$set: {"b": [{"f":"b"}]}})
> db.test.find()
{ "_id" : ObjectId("5102c8868e48734ea1220a9d"), "a" : 1, "b" : [ { "f" : "b" } ] }

Upvotes: 0

Prakash Murthy
Prakash Murthy

Reputation: 13077

update({"name" : "nick"}, {"age" : 50}) replaces the complete object with only {"age" : 50}.

Running find({"name" : "nick" }) after running the above update would return no document found error.

Using $set would allow to update only the "age" param of the original object.

Karl Seguin's Little Mongodb Book has a very good explanation about the difference between replace and set.

Upvotes: 6

Related Questions