Reputation: 4714
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" }
]
Upvotes: 2
Views: 1040
Reputation: 41440
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:
Upvotes: 6