MongoDB remove an item from an array inside an array of objects
Asked Answered
W

1

13

I have a document that looks like this:

{
  "_id" : ObjectId("56fea43a571332cc97e06d9c"),
  "sections" : [
    {
      "_id" : ObjectId("56fea43a571332cc97e06d9e"),
      "registered" : [
        "123",
        "e3d65a4e-2552-4995-ac5a-3c5180258d87"
      ]
    }
  ]
}

I'd like to remove the 'e3d65a4e-2552-4995-ac5a-3c5180258d87' in the registered array of only the specific section with the _id of '56fea43a571332cc97e06d9e'.

My current attempt is something like this, but it just returns the original document unmodified.

db.test.findOneAndUpdate(
{
  $and: [
    {'sections._id': ObjectId('56fea43a571332cc97e06d9e')},
    {'sections.registered': 'e3d65a4e-2552-4995-ac5a-3c5180258d87'}
  ]
},
{
  $pull: {
    $and: [
      {'sections._id': ObjectId('56fea43a571332cc97e06d9e')},
      {'sections.registered': 'e3d65a4e-2552-4995-ac5a-3c5180258d87'}
    ]
  }
})

I've looked in to $pull, but I can't seem to figure out how to make it work on an array of nested objects containing another array. The $pull examples all seem to deal with only one level of nesting. How do I remove the matching entry from the registered array of the item in the sections array with the _id that I supply?

Wivern answered 12/4, 2016 at 16:40 Comment(0)
P
10

You need to use the positional $ update operator to remove the element from your array. You need this is because "sections" is an array of sub-documents.

db.test.findOneAndUpdate(
    { "sections._id" : ObjectId("56fea43a571332cc97e06d9e") }, 
    { "$pull": { "sections.$.registered": "e3d65a4e-2552-4995-ac5a-3c5180258d87" } } 
)
Paradise answered 12/4, 2016 at 17:21 Comment(4)
Won't this remove any instance of "e3d65a4e-2552-4995-ac5a-3c5180258d87" in any of the sections? I want to only remove that string from the registered array of the specific section.Wivern
Ok after testing this appeared to work, but I have no idea why. How does it know to only apply the $pull operator to the specific section with the matching _id?Wivern
Ok I actually read the docs for $ like a human being. This makes sense. Thanks for your help.Wivern
what if i have to remove more than one element form that array @sstyvaneAsclepiadaceous

© 2022 - 2024 — McMap. All rights reserved.