2

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

Community
  • 1
  • 1
Mark Thien
  • 878
  • 2
  • 13
  • 31

1 Answers1

2

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

{
   _id: ObjectId("5785d10570d6c39923d476cf"), 
   "transaction": {
      "$elemMatch": {     
        "amount": 0, 
        "type": "TYPE1", 
        "id": "nhaa94" 
   }
}
DAXaholic
  • 28,212
  • 5
  • 58
  • 67