node.jsmongodbexpressmongodb-queryfindandmodify

Mongo DB findAndModify query


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?


Solution

  • 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 ObjectIds, like for example: ObjectId("5883ee408d4f6e2b748bf57b")