-1

Schema:

{
  A: [
    { name: "string", age: "integer" },
    { name: "string", age: "integer" },
    { name: "string", age: "integer" },
    ...
  ]
}

compound index:

{
  "A.name": 1,
  "A.age": 1,
}

query

db.col.aggregate([
  { $match: { A: { $elemMatch: { name: "XYZ"  } } } },
  { $sort: { "A.age": 1 } }
  { $set: ... }
  ...
  { $limit: 10 }
])

The above query will sort the array based on all of the subdocuments of A.

How to get it to sort just based on the matching subdocuments? And then also to use the index?

  • Would you please shere what **output you needed** and **one example of document** ? i am confused your array is a document or part of document as a subdocument – Nishang Raiyani May 09 '23 at 02:08
  • "The above query will sort the array based on all of the subdocuments of A." No it, does not! It will sort the documents, not the array. `{ $sort: { "A.age": 1 } }` will sort on the **first** element of `A` – Wernfried Domscheit May 09 '23 at 08:27
  • Arrays are funny in mongodb, see the comparison/sort order: https://www.mongodb.com/docs/manual/reference/bson-type-comparison-order/#arrays – Joe May 09 '23 at 16:52

1 Answers1

0

You can use $sortArray Aggregation Pipeline Operator

db.collection.aggregate( [
   // ... previous Aggregation Stages 
   { $project:
      {
          _id: 0,
          result:
            {
               $sortArray: { input: "$A", sortBy: { name: 1 ,age: 1} }
            }
      }
   }
] )