2

I have the following code:

db.users.save({ username: "admin", array: [{ foo1: "foo1", foo2: "foo2" }, { bar1: "bar1", bar2: "bar2" }, { cell1: "cell1", cell2: "cell2" } ] }); 

Now I want to update the array. I mean to push something into the array:

db.users.update({ username: admin }, { $set: { array: { push1: "push1", push2: "push2" } }, function (err, updated) { 

The update function doesn't push. So how can I push to the array, so the result will be:

[ { foo1:"foo1", foo2:"foo2" }, { bar1:"bar1", bar2:"bar2" }, { cell1:"cell1", cell2:"cell2" }, { push1:"push1", push2:"push2" } ] 

1 Answer 1

6

The $set operator will, of course, change the whole data of the array property.

If you want to just push, use $push (which pushes one item at once) or $pushAll (which pushes all items of an array).
If you want to push without repeating an item, use $addToSet.

Note: If you're on MongoDB 2.4 (the latest version), use $push with the new $each modifier. This deprecates usage of $pushAll (this applies to $addToSet, too)

Docs:

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.