简体   繁体   中英

How to query and sort nested array in mongodb?

So first things first, here is the data model

数据模型样本

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

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}}
]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM