【问题标题】:node.js mongodb only update first found subdocument in arraynode.js mongodb 仅更新数组中第一个找到的子文档
【发布时间】:2016-08-22 04:19:53
【问题描述】:

一个用户集合:

{

"_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

【问题讨论】:

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


    【解决方案1】:

    尝试使用$elemMatch 运算符来使用这样的查询

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

    【讨论】:

    • 你是我的英雄!!
    猜你喜欢
    • 1970-01-01
    • 2022-12-05
    • 2016-12-31
    • 1970-01-01
    • 2020-05-01
    • 2015-08-26
    • 1970-01-01
    • 2015-03-30
    • 2020-10-02
    相关资源
    最近更新 更多