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

1 Answer 1

2

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

{
   _id: ObjectId("5785d10570d6c39923d476cf"), 
   "transaction": {
      "$elemMatch": {     
        "amount": 0, 
        "type": "TYPE1", 
        "id": "nhaa94" 
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

you are my hero !!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.