node.js mongodb只更新数组中第一个找到的子文档

时间:2016-08-22 04:19:53

标签: node.js mongodb mongodb-query mongodb-update

用户集合:

{

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

}

更新声明

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) {

}

更新为transaction.id = "m69bkn"而不是"nhaa94" 它只是更新我猜的第一个找到的子文档 我一直在这里搜索

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

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

Updating an array item using NodeJS, MongoDB & Monk

1 个答案:

答案 0 :(得分:2)

尝试使用$elemMatch运算符

来使用这样的查询
{
   _id: ObjectId("5785d10570d6c39923d476cf"), 
   "transaction": {
      "$elemMatch": {     
        "amount": 0, 
        "type": "TYPE1", 
        "id": "nhaa94" 
   }
}