0

I am having the following projects document:

{
    "_id":"59f96bd3108265ce6904e0b6",
    "posts":[
        {
            "id":"b37108dc-d27f-49fa-ab9d-4d4fd5c9484b",
            "accounts":["59fe8725108265c739a08b67", "59fad4d9108265572001dd49"]
        },
                    {
            "id":"b37108dc-d27f-49fa-ab9d-4d4fd5c9484b",
            "accounts":["59fe8725108265c739a08b67","59dae438cc0a312805e70ada"]
        },
                    {
            "id":"b37108dc-d27f-49fa-ab9d-4d4fd5c9484b",
            "accounts":["59fe8725108265c739a08b67","59dae438cc0a312805e70ada"]
        }
    ]
}

I want to pull/remove 59fe8725108265c739a08b67 from posts.$.accounts. I tried following query.

db.projects.update(
    {"_id" : "59f96bd3108265ce6904e0b6"}, 
    { "$pull": { "posts.$.accounts": {$in: ["59fe8725108265c739a08b67"]} } })

But somehow it's not working. It always returns me:

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: posts.$.accounts" } })

Minato Namikaze
  • 576
  • 1
  • 7
  • 22
  • If you want to `$pull` from a nested array, you need to match the first "outer" element it is in. If you expect to remove from ALL arrays for the matching path, read the answers that tell you you cannot YET do this in a single request. Relevant answers marked that you need to read. – Neil Lunn Nov 06 '17 at 03:06
  • You only matched the document. Read the linked answers again. What you are missing is either `"posts._id": "b37108dc-d27f-49fa-ab9d-4d4fd5c9484b"` or similar depending on which "outer" array to pull from. Or you are still missing that you cannot do this to ALL of the array elements at once. – Neil Lunn Nov 06 '17 at 03:18
  • I dont have `posts.id` available, so will it be possible? – Minato Namikaze Nov 06 '17 at 03:18
  • Read the existing answers that actually answer your question. That's why you were pointed at them – Neil Lunn Nov 06 '17 at 03:22

0 Answers0