47

$addToSet operator adds a value to an array only if the value is not already in the array. If the value is in the array, $addToSet does not modify the array.

I want to insert two values that should not be duplicated via one request. Is this possible?

I tried to pass an array to $addToSet operator but it inserted an array instead of each value from that array.

$ mongo test
MongoDB shell version: 2.4.9
connecting to: test
> db.c.insert({a: [1, 2, 3]})
> db.c.find()
{ "_id" : ObjectId("53511a255a82cd559393d840"), "a" : [ 1, 2, 3 ] }
> db.c.update({}, {$addToSet: {a: [2, 4]}})
> db.c.find()
{ "_id" : ObjectId("53511a255a82cd559393d840"), "a" : [ 1, 2, 3, [ 2, 4 ] ] }

2 Answers 2

102

From the docs for $addToSet:

If the value is an array, $addToSet appends the whole array as a single element. To add each element of the value separately, use $addToSet with the $each modifier. See Modifiers for details.

So you should use this instead:

db.c.update({}, {$addToSet: {a: {$each: [2, 4]}}})
Sign up to request clarification or add additional context in comments.

Comments

7

Yep. But you need the $each modifier to be added in your statement:

db.c.update({},{ $addToSet: { a: {$each: [ 2, 4 ] } } })

And the result:

{ "a" : [ 1, 2, 3, 4 ] }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.