Warm tip: This article is reproduced from stackoverflow.com, please click
mongodb aggregation-framework aggregate-functions

Remove element from array aggregate

发布于 2020-03-29 21:03:31

How can I loop through an array and remove a specific element based on a field.

Here is the layout I have - it is in a collection called cases:

** The collection contains a companyID, cases [Array], lastModified **

enter image description here

So I will have to use an aggregate to unwind the cases and then search for the casenumber where it equals '17':

db.cases.aggregate([
    { $match: { companyID: 218}},
    { $unwind: '$cases' },
    { $match: {'cases.casenumber': '17'} }
])

This returns:

enter image description here

But now I want to delete just that specific item.

Thanks.

Questioner
Andrew
Viewed
84
Grégory NEUT 2020-01-31 19:00

You can use of an updateMany request. First argument is the matching condition, the second is the action.

$pull is a special keyword that will remove matching elements from arrays.

   db.collection.updateMany({
       companyID: 218,
    }, {
       $pull: {
          cases: {
             casenumber: 17,
          },
       },
    })

https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/

https://docs.mongodb.com/manual/reference/operator/update/pull/


Example from the doc :

db.profiles.update( { _id: 1 }, { $pull: { votes: { $gte: 6 } } } )