Search code examples
arraysmongodbsortingmongodb-querylimit

How to get entire list of nested inner list groups, and add sort & limit to them. MongoDB query


I have the following model of an object called EvaluationsGroup in a MongoDB collection:

{
    "_id" : "5fecfb83d61ae459df1bceda",
    "Status" : "noDataFound",
    "Evaluations" : [ 
        {
            "EvaluatedAt" : ISODate("2020-12-30T22:13:21.168Z"),
            "ReferenceValue" : 2.0
        }
        {
            "EvaluatedAt" : ISODate("2020-12-30T22:13:15.168Z"),
            "ReferenceValue" : 3.0,
             (... several other properties)
        }
    ]
}

What I want to do is get the entire list of all inner Evaluations of all the 'EvaluationsGroups' indistinctively, sort them by EvaluatedAt date, and limit the results for paging.

How would I make such a query in mongo?


Solution

    • $project to show required fields
    • $unwind deconstruct Evaluations array
    • $replaceRoot to replace object in root
    • $sort by EvaluatedAt date in descending order
    • $skip number of documents for pagination
    • $limit number of documents
    let page = 0;
    let limit = 10;
    let skip = page*limit;
    db.collection.aggregate([
      {
        $project: {
          _id: 0,
          Evaluations: 1
        }
      },
      { $unwind: "$Evaluations" },
      { $replaceRoot: { newRoot: "$Evaluations" } },
      { $sort: { EvaluatedAt: -1 } },
      { $skip: skip },
      { $limit: limit }
    ])
    

    Playground