Mongodb arrays - $pull from embedded document

Viewed 48
{
    "_id" : ObjectId("60605d10f9c97907028172f5"),
    "dbname" : "123456789-123456789",
    "logindetails" : [
        {
            "email" : "ankit@gmail.com",
            "password" : "$2a$04$i7AGR.zG113mjIshA.Me7O/Wv9zIcuBy58GOqb2Gf76Xk5WgYxGIu",
            "sessionid" : [
                "bca0deeb-66ed-4f1e-8d76-7ea2f04102b1"
            ],
            "name" : "Ankit",
            "initial" : "ab",
            "updateToken" : ""
        }
    ]
}

In my Mongodb collection userDetails, I have the above document, I want to remove sessionid value. I am using the following query :

db.userDetails.updateOne({"dbname":"123456789-123456789"},{"$pull":{"logindetails.sessionid":"bca0deeb-66ed-4f1e-8d76-7ea2f04102b1"}})

I am getting the following error :

"errmsg" : "Cannot use the part (sessionid) of (logindetails.sessionid) to traverse the element ({logindetails: [ { email: \"ankit.s.bagaria@gmail.com\", password: \"$2a$04$i7AGR.zG113mjIshA.Me7O/Wv9zIcuBy58GOqb2Gf76Xk5WgYxGIu\", sessionid: [ \"bca0deeb-66ed-4f1e-8d76-7ea2f04102b1\" ], name: \"Ankit Bagaria\", initial: \"ab\", updateToken: \"\" } ]})"

What will be the correct query?

1 Answers

Demo - https://mongoplayground.net/p/LgYjRIUzSlJ

Use https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/

The filtered positional operator $[] identifies the array elements that match the arrayFilters conditions for an update operation

Used in conjunction with the arrayFilters option, the $[] operator has the following form:

db.collection.update(
{"dbname": "123456789-123456789" },
{ "$pull": { "logindetails.$[l].sessionid": "bca0deeb-66ed-4f1e-8d76-7ea2f04102b1" } },
{ arrayFilters: [ { "l.sessionid": "bca0deeb-66ed-4f1e-8d76-7ea2f04102b1" } ]}
)
Related