Gratis Devs
Gratis Devs

Reputation: 165

Fetch only those array elements in mongodb that satisfy the condition

Suppose I have below test collection in MongoDB:

[
  {name: "vipul",arr:[1,2,3,4,5,6,7,8]},
  {name: "rahul",arr:[3,4,5,6,7,8,9,10]},
]

Now if I do below query:

db.test.find({"arr":{$gt: 5});

The above query returns the below output:

[
  {name: "vipul",arr:[1,2,3,4,5,6,7,8]},
  {name: "rahul",arr:[3,4,5,6,7,8,9,10]},
]

But I need only those elements that match the condition, like below:

[
  {name: "vipul",arr:[6,7,8]},
  {name: "rahul",arr:[6,7,8,9,10]},
]

I know this can be done using aggregation, but I want to do it without aggregation. Is there any method to do it??

Thanks!

Upvotes: 0

Views: 38

Answers (1)

Yong Shun
Yong Shun

Reputation: 51485

Add $filter for the arr field in the projection.

db.collection.find({
  "arr": {
    $gt: 5
  }
},
{
  "name": 1,
  "arr": {
    $filter: {
      input: "$arr",
      cond: {
        $gt: [
          "$$this",
          5
        ]
      }
    }
  }
})

Sample Mongo Playground

Upvotes: 1

Related Questions