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 **
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:
But now I want to delete just that specific item.
Thanks.
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 } } } )
I looked into that but it wouldn't remove it - I thought it was possibly due to the fact that it needed to unwind the array first? It says Acknowledged is true, but matchedCount and modifiedCount are 0. Oh and just incase this makes a difference, 17 is a string. I have put the '' around it when testing
@Andrew I should reproduce your schema to try this one, unfortunately I have no time right now. I'll do it later if no one answered your question by then.
Really sorry - this worked, I forgot to change the name of the collection. Thank you very much
Great! :) glad that you figured this one out