Search code examples
mongodbfilteraggregation

How to filter the main array in mongodb aggregation


Imagine an array coming to a step in aggregation pipeline like below:

[{
  name: "John",
  address: { zip: 1111 }
},{
  name: "Doe",
  address: { zip: 2222 }
}]

So, now if I want to filter all the objects which are address.zip: 2222, how that aggregation stage would look like? I'm a bit confused with the documentation because it only shows the way to implement the $filter in a subarray to filter the items in the subarray itself.

I know that this can be achieved if I just used the find() function but here the issue is up to the previous stage, things are dynamically generated so I need to find a way to filter this in the aggregation itself.

Any help regarding this is much appreciated. Thanks!


Solution

  • $match ?

    db.collection.aggregate([
      {
        "$match": {
          address: {
            zip: 2222
          }
        }
      }
    ])
    

    mongoplayground