removing object from nested array of objects mongodb

后端 未结 2 1472
别那么骄傲
别那么骄傲 2021-01-20 17:11

I\'ve got collection with volunteer information in it, and it lists the volunteers as an array of objects. I can display all the shifts for each volunteer, but removing one

相关标签:
2条回答
  • 2021-01-20 17:45

    Try this

    db.example.update(
     {},
     { $unset: {"Mary Mack":1}},
     false, true
    )
    
    0 讨论(0)
  • 2021-01-20 17:47

    You can do this by specifying something to match the "document" and then the required "shifts" array entry as the query expression for an .update(). Then apply the positional $ operator for the matched array index with $pull:

    db.collection.update(
     { "_id": ObjectId("59180305c19dbaa4ecd9ee59"), "shifts.timeslot": "8:00 - NOON" },
     { "$pull": { "shifts.$.volunteers": { "fullname": "Mary Mack" } } }
    )
    

    That is okay in this instance since you are only trying to "match" on the "outer" array in the nested structure and the $pull has query arguments of it's own to identify the array entry to remove.

    You really should be careful using "nested arrays" though. As whilst a $pull operation like this works, updates to the "inner" array are not really possible since the positional $ operator will only match the "first" element that meets the condition. So your example of "Mary Mack" in multiple shifts would only ever match in the first "shifts" array entry found.

    0 讨论(0)
提交回复
热议问题