In MongoDB, there is a piece of data as follows, which I want to modify.workerStats.stage=LABEL and workerStats.idOfWorker=admin
Thestats
insidelabeledItems
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 it be modified?
$elemMatch
It 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 } })