Search code examples
node.jsmongodbmongodb-querymongodb-update

node.js mongodb only update first found subdocument in array


a User collection:

{

"_id" : ObjectId("5785d10570d6c39923d476cf"),
"name" : "BB Cafe",
"transaction" : [ 
        {
            "id" : "m69bkn",
            "type" : "TYPE1",
            "amount" : 0,
        },
        {
            "id" : "nhaa94",
            "type" : "TYPE1",
            "amount" : 0,
        }
]

}

update statement

var mongodbObjectID = require('mongodb').ObjectID;

 db.collection('user').update(
        {_id:new mongodb.ObjectID("5785d10570d6c39923d476cf"), 
          "transaction.amount":0, 
          "transaction.type":"TYPE1", 
          "transaction.id":"nhaa94"
        }, {$set:{"transaction.$.amount":0.6}}, {w:1}, function(err, resultUpdate) {

}

It updated to transaction.id = "m69bkn" instead of "nhaa94" It just update the first found subdocument I guess I have been searching here in SO like

update array with $ is not working in mongodb-native nodejs

and

https://docs.mongodb.com/manual/reference/operator/update/positional/

and

Updating an array item using NodeJS, MongoDB & Monk


Solution

  • Try to use a query like this using the $elemMatch operator

    {
       _id: ObjectId("5785d10570d6c39923d476cf"), 
       "transaction": {
          "$elemMatch": {     
            "amount": 0, 
            "type": "TYPE1", 
            "id": "nhaa94" 
       }
    }