Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 440
Scoopa Avatar asked May 25 '26 14:05

Scoopa


2 Answers

$match ?

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

mongoplayground

like image 143
YuTing Avatar answered May 28 '26 04:05

YuTing


Would be

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

$filter is used to remove elements from an Array, e.g.

{ $filter: { input: [ 1,2,3,4,5,6 ], cond: {$lt: ["$$this", 4] } } } => [1,2,3]
like image 28
Wernfried Domscheit Avatar answered May 28 '26 04:05

Wernfried Domscheit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!