'$elemMatch' functionality

Can someone please explain the correct application of ‘$elemMatch’ functionality.
mongoDb document suggest that elemMatch needs to be used for multi-field condition while updating embedded arrays.

Mentioned example:

db.students.updateOne(
   {
     _id: 5,
     grades: { $elemMatch: { grade: { $lte: 90 }, mean: { $gt: 80 } } }
   },
   { $set: { "grades.$.std" : 6 } }
)

but the same can be achieved with:

db.students.findOneAndUpdate(
{ 
  _id : 5, 
  "grades.grade" : { $lte : 90}, "grades.mean" : { $gt : 80} }, 
{ $set : { "grades.$.std" : 6}
})

What is the use case for ‘elemMatch’ operator?

1 Like

Hello @Abhishek_Kumar_Singh,

There is a similar topic, it will help you to understand the difference,