Reputation: 185
JSON Object:
{
"_id" : ObjectId("123"),
"pi" : [
{
"si" : 0,
"ui" : {
"_id" : ObjectId("xyz"),
"un" : "xyz",
"his" : 27,
}
},
{
"si" : 1,
"ui" : {
"_id" : ObjectId("zyx"),
"un" : "zyx",
"his" : 18,
}
}
],
}
Operation:
db.getCollection('playing_table').findAndModify(
{"_id" : ObjectId("123") ,"pi.ui._id":ObjectId("xyz")},
{},
{$inc : {'pi.$.ui.his' : 1}},
{new : true},
function (err, updata) {});
I want to increase his counter using findAndModify()
query.
Is it possible?
Upvotes: 0
Views: 138
Reputation: 11291
Assuming that all the ui._id
's are unique, this one will work for you:
db.getCollection('playing_table').findAndModify({
query: {
"pi": { $elemMatch: { "ui._id" : ObjectId("xyz") } }
},
sort: {},
update: { $inc: { "pi.$.ui.his" : 1 } }
})
It will result in:
{
"_id" : ObjectId("123"),
"pi" : [
{
"si" : 0,
"ui" : {
"_id" : ObjectId("xyz"),
"un" : "xyz",
"his" : 28, // incremented
}
},
{
"si" : 1,
"ui" : {
"_id" : ObjectId("zyx"),
"un" : "zyx",
"his" : 18,
}
}
],
}
Do adjust your ObjectId
s, like for example: ObjectId("5883ee408d4f6e2b748bf57b")
Upvotes: 1