Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb getting on simple $push The positional operator did not find the match needed from the query

I have this simple update api invocation : this is my document :

{
        "_id" : ObjectId("577a5b9a89xxx32a1"),
        "oid" : {
                "a" : 0,
                "b" : 0,
                "c" : NumberLong("1260351143035")
        },
        "sessions" : [
                {

                }
        ]
}

Then i try to insert 1 element into sessions array :

db.getCollection('CustomerInfo').update({"oid.c":1260351143035},{$push:{"sessions.$.asessionID":"test123"}}) 

but im getting this error:

WriteResult({
        "nMatched" : 0,
        "nUpserted" : 0,
        "nModified" : 0,
        "writeError" : {
                "code" : 16837,
                "errmsg" : "The positional operator did not find the match needed from the query. Unexpanded update: sessions.$.asessionID"
        }
})

using $set im getting the same error

like image 898
user63898 Avatar asked Mar 11 '23 19:03

user63898


1 Answers

As the error implies,

"The positional operator did not find the match needed from the query. Unexpanded update: sessions.$.asessionID",

the positional operator will work if the array to be updated is also part of the query. In your case, the query only involves the embedded document oid. The best update operator to use in your case is the $set instead.

You can include the sessions array in the query, for example:

db.getCollection('CustomerInfo').update(
    { 
        "oid.c": 1260351143035,
        "sessions.0": {} // query where sessions array first element is an empty document
        /* "sessions.0": { "$exists": true } // query where sessions array first element exists */
    },
    {
        "$set": { "sessions.$.asessionID": "test123" }
    }
) 
like image 62
chridam Avatar answered Apr 22 '23 09:04

chridam