MongoDB嵌套文档如何局部更新

新手上路,请多包涵

MongoDB中,有如下的一条数据,我想修改,workerStats.stage=LABEL and workerStats.idOfWorker=adminstats里面的labeledItems,使其自增1。

{
    "_id" : ObjectId("5ac1ff4c87c0fc67c0f4fe60"),
    "_class" : "com.JobEntity",
    "workerStats" : [ 
        {
            "idOfWorker" : "admin",
            "stage" : "LABEL",
            "stats" : {
                "totalItems" : 0,
                "labeledItems" : 0,
                "submittedItems" : 0
            }
        }, 
        {
            "idOfWorker" : "lgh",
            "stage" : "REVIEW",
            "stats" : {
                "totalItems" : 0,
                "labeledItems" : 0,
                "submittedItems" : 0
            }
        }
    ]
}

我的修改语句如下:

db.job.updateOne(
{
    "_id": ObjectId("5ac1ff4c87c0fc67c0f4fe60"),
    "workerStats.stage": "LABEL",
    "workerStats.idOfWorker": "admin"
},
{
    $inc: {
        "workerStats.$.stats.labeledItems": 1
    }
}
)

但是并不起作用,请问应该如何修改?

阅读 4.5k
1 个回答

$elemMatch才是代表使用同一个数组元素同时匹配多个条件。否则可能是多个数组元素匹配不同的条件,$也就没有意义了。

db.test.updateOne(
{
    _id: ObjectId("5ac1ff4c87c0fc67c0f4fe60"),
    workerStats: {
        $elemMatch: {
            stage: "LABEL",
            idOfWorker: "admin"
        }
    }
},
{
    $inc: {
        "workerStats.$.stats.labeledItems": 1
    }
})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进