0

I a mongo db collection called exampleCollection. Inside of the collection are documents. The documents have a property called members.

db.collection('exampleCollection).find({ 'members._id': 'memberId1' })

yeilds

[
   { 
      "_id" : "exampleId1", 
      "members": [
         { "_id": "memberId1", "removed" : true },
         { "_id": "memberId2" }
      ]
   },
   { 
      "_id" : "exampleId2", 
      "members": [
         { "_id": "memberId1" },
         { "_id": "memberId", "removed" : true }
      ]
   }
]

I am trying to formulate a query that would eliminate the members marked as removed. Right now it seems as though the best that I can do is remove examples with members which are marked as removed. I just want to eliminate the items in the nested members arrays.

I'm wondering if this is possible. I suspect that I might have to split this document up into multiple collections but I would like to know if this is possible first.

xerotolerant
  • 1,955
  • 4
  • 21
  • 39
  • 1
    You use [`$filter`](https://docs.mongodb.com/manual/reference/operator/aggregation/filter/) for this as shown in the answers. Of course you want the condition where "not true" so you would use a negation operator like [`$ne`](https://docs.mongodb.com/manual/reference/operator/aggregation/ne/) in the comparison. – Neil Lunn Nov 01 '17 at 22:48
  • Specifically `{ "$addFields": { "members": { "$filter": { "input": "$members", "cond": { "$not": ["$$this.removed"] } } } }}` actually. [`$not`](https://docs.mongodb.com/manual/reference/operator/aggregation/not/) is shorter since the value is actually boolean, or `null` when not there. – Neil Lunn Nov 01 '17 at 23:01

0 Answers0