How do I remove a specific object from array in MongoDB depending on the count?

Viewed 34

This image for reference

enter image description here

How do I make it so that when a specific object's count is "0" in the array, it would be removed from the array. Currently, the issue here is that: Despite the object count being 0, its still in the array. I want to make it so that if the object's count is 0, it wont show in the array. It would be removed.

This is the code. (If the code is incorrect, let me know what I did wrong)

      if(getCount(newItem._id) === 0) {
            collection.update(
                { _id: newItem._id },
                { $pull: { _id: newItem._id }
             }
        );
1 Answers

You can use $filter for this. This query will remove items with 0 count from all you documents. If you want to limit it to specific documents, put the condition on the first {}:

db.collection.update(
{},
[{$set: {Inventory: {$filter: {input: "$Inventory", cond: {$ne: ["$$this.count", 0]}}}}}]
)

See how it works on the playground example

Related