How to update MongoDB nested documents locally

In

MongoDB, there is a piece of data that I want to modify, workerStats.stage=LABEL and workerStats.idOfWorker=admin stats in labeledItems to increase it by 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
            }
        }
    ]
}

my modification statement is as follows:

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

but it doesn"t work. How should I modify it?


$elemMatch means to use the same array element to match multiple conditions at the same time. Otherwise, it may be that multiple array elements match different conditions, and $is meaningless.

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