Home > Net >  How to query and sort nested array in mongodb?
How to query and sort nested array in mongodb?

Time:09-16

So first things first, here is the data model

data model sample

All i want is do a find where the result is a list of applications sorted by date and limited by 5 elements

CodePudding user response:

Projection will give only the desired fields of a document, in this case, if you want only the applications list with the _id field you could mention that in $project as shown below in the query, and the result is sorted by appliedDate field descending order (most recent ones comes first) and limited 5 records.

Assuming your collection name is test you could fire the below query to achieve the desired results:

db.test.aggregate([
  {$unwind: "$applications"}, 
  {$sort: {"applications.appliedDate": -1}}, 
  {$group: {_id:"$_id", applications: {$push:"$applications"}}},
  {$limit: 5},
  {"$project": {"applications": 1}}
]);
  • Related