Friday, 20 February 2015

mongoDB : $addToSet : add value to array if value not exist


The $addToSet operator adds a value to an array only if the value is not already in the array.

Syntax
{ $addToSet: { <field1>: <value1>, ... } }


> db.sample.find()
{ "_id" : 1, "arr" : [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] }
{ "_id" : 2, "arr" : [ 9, 8, 7, 6, 5, 4, 3, 2, 1 ] }
{ "_id" : 3, "arr" : [ 19, 6, 14 ] }
{ "_id" : 4, "arr" : [ 3, 6, 5, 104, 302, 161 ] }
{ "_id" : 5, "arr" : [ 1, 6, 5, 5, 4 ] }
>
>
> db.sample.update({"_id":5}, {$addToSet : {"arr" : 5}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
>
> db.sample.find({"_id" : 5})
{ "_id" : 5, "arr" : [ 1, 6, 5, 5, 4 ] }
>
> db.sample.update({"_id":5}, {$addToSet : {"arr" : 2}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
>
> db.sample.find({"_id" : 5})
{ "_id" : 5, "arr" : [ 1, 6, 5, 5, 4, 2 ] }


Observe above code sample, addToSet don’t modify document 5 while inserting value 5 (since 5 already exist), but it updated document 5 while inserting value 2 (since 2 not exist).



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment