How to filter all elements in array that must satisfy the condition (using find())

Hi All,
I want to filter documents with elements in the array that must satisfy the condition (using find()). I tried many ways, including $elemMatch, but still not correct.
Thanks for your advice.

Hello @Trung_Tran_The, Welcome back to the MongoDB community developer forum,

You need to filter it by $filter operator in projection,

db.students.find(
  { grades: { $elemMatch: { $gte: 98 } } },
  {
    grades: {
      $filter: {
        input: "$grades",
        in: {
          $gte: ["$$this", 98]
        }
      }
    }
  }
)
2 Likes

Thanks for your answer,

I tried it but the result still exists _id: 2. It only removes element with value < 98 (=95), document with _id: 2 still exists.

db.<collectionName>.find( { < filter > }, { < project > } )
I want to find process in < filter >, not process in < project >

My code:

db.students.find( 
  { grades: { $elemMatch: { $gte: 98 } } }, 
  { grades: { 
     $filter: { 
        input: "$grades",
        as: 'data',
        cond: { $gte: ["$$data", 98] } 
} } })

What are you expecting? can you show the expected result, In your first post’s screenshot, you have strikeout the 95 in _id: 3, so I thought you want values that are greater than or equal to 98.

Do you mean all the elements in grades should be greater than or equal to 98? then try $all operator inside $elemMatch to check for all elements,

db.students.find({
  grades: {
    $elemMatch: {
      $all: [98]
    }
  }
})

I tried it but the result still exists _id: 2. It only removes element with value < 98 (=95) , document with _id: 2 still exists .

Sorry bro, I mean _id: 3.
If all elements are >= 98 then the current document will be retrieved. Otherwise, no

You can try this, using $not with $lt operator,
But this will return grades.grade array of objects documents, so I have added a condition for that to don’t return.

db.students.find({
  grades: {
    $not: {
      $lt: 98
    }
  },
  "grades.grade": {
    $exists: false
  }
})

I will update you if there are any other possibilities to achieve this.

1 Like

This is a nice solution, thanks bro!

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.