Varun Oberoi
Varun Oberoi

Reputation: 692

MongoDb's $ (update) does not update array's element but rather replace it?

I want to update an element of an array inside mongodb's document (I am using mongoose). Schema is something like:

{
 ..
 arr : [{
  foo: Number,
  bar: [String],
  name: String
 }]
 ..
}

And my query is:

SomeModel.update({
 _id: "id of the document",
 arr: {
  $elemMatch: {
   _id: "_id assigned by mongoose to array element"
  }
 }
}, {
 'arr.$': {
  name: 'new name'  
 }
}).exec()

It just replaces whole array element say:

{
 _id: "some objectId",
 name: 'old name',
 foo: 0,
}

to:

{
 name: 'new name'
}

what I want:

{
 _id: "some objectId",
 name: 'new name',
 foo: 0,
}

What I am curious to know if it is possible to achieve this in single update query ? (May be there is a silly mistake in my query :P or another approach)

I would also like to do update query like so:

{
 $inc: { foo: 1},
 $push: { bar: "abc"}
}

Upvotes: 0

Views: 1673

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151122

If you are still struggling with the whole implementation the full application of your statement is as follows:

SomeModel.update(
    {
        "arr._id": "123"
    },
    {
        "$set": { "arr.$.name": "new name" },
        "$inc": { "arr.$.foo": 1},
        "$push": { "arr.$.bar": "abc" }
    }
)
,function(err,numAffected) {

});

So each operation is performed in turn.

Upvotes: 1

Related Questions