0
{
  tests: [
    { grade: 90  },
    { grade: 80  },
    { grade: 100 },
    ...
  ]
}

This is the schema of my collection.

I have an index on tests.grade.

In my aggregation pipeline, after $elemMatch inside of a $match, there will be

[
  { $match: { tests: { $elemMatch: { grade: { $gt: 50 } } } } },
  { $sort: { "tests.grade": 1 } },
  { $limit: 10 }
]

My question is, will this work, given that tests.grade is a field inside of an array of embedded documents? Would it know to use the embedded doc that was matched in the elemMatch? What if there are multiple matches? Would this be optimized as in ESR rule?

  • Neither `$elemMatch` nor `$match` will remove elements from the array. – Joe Mar 09 '23 at 01:38
  • I know that. So are you saying the sorting will not work? – Bear Bile Farming is Torture Mar 09 '23 at 02:17
  • Considering [how arrays are sorted](https://www.mongodb.com/docs/manual/reference/bson-type-comparison-order/#arrays), a multi-key index wouldn't be much help for the sort. – Joe Mar 09 '23 at 02:20
  • Based on the two questions at the end of the description, I suspect that this pipeline is not doing what you expect. _All_ `tests.grade` values from the matching documents (not just those that pass the `$elemMatch` predicate) will be considered for the sort. This is, I believe, what @Joe's two comments together are stating as well. I think [this playground](https://mongoplayground.net/p/2oA69GnSBP3) provides a good demonstration. In short - the index will help with the `$match` but not with the `$sort`. – user20042973 Mar 09 '23 at 13:54

0 Answers0