1

I'm working on mongo, in this time in need to remove a specific element from array nested in another one, the structure is like the following:

{ 
    "_id" : ObjectId("5e616314946b6d3ac4ed8252"), 
    "uid" : "5db069478556622b4a0adca5", 
    "areas" : [
        {
            "name" : "mexico", 
            "elements" : [
                "23452345", 
                "24454675"
            ], 
        }, 
        {
            "name" : "usa", 
            "elemets" : [
                "123123123", 
                "1234334"
            ], 
        }
    ]
}

So I need a query that lets me remove any element in "elements" property.

I tried with this query but I couldn't reach it.

db.areas.update(
    { },
    { $pull: 
        { areas: { 
            $elemMatch: { 
                elements: { $eq : "123123123" }
                }
            }
        }
    },
    { multi:false }
);

This just said

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
3
  • Replace areas: by "areas.$[]:" Commented Mar 11, 2020 at 20:37
  • elements: { $eq : "123123123" } you can shortcut to elements: "123123123" Commented Mar 11, 2020 at 20:39
  • 1
    The input documents you have posted has some inconsistency; the sub-array field elements is different for the name: "usa"; it says elemets. Commented Mar 12, 2020 at 6:31

1 Answer 1

1

Here is the update for removing the specific array element in a sub-array (elements).

Note that to remove (pull) the specified element (elements value "24454675"), you need to specify the outer-array's element matching condition (note that there are two elements in the outer-array field areas).

db.areas.update(
   { "areas.name": "mexico" },
   { $pull: { "areas.$.elements":  "24454675" } }
)

NOTE: If you don't specify the { "areas.name": "mexico" } condition, the whole sub-document of the areas array will be removed.

Sign up to request clarification or add additional context in comments.

1 Comment

I've been trying to pull areas.elements but it keeps showing errmsg. It was areas.$.elements. Thanks for the answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.