简体   繁体   English

如何对mongodb中的嵌套数组进行查询和排序?

[英]How to query and sort nested array in mongodb?

So first things first, here is the data model所以首先,这是数据 model

数据模型样本

All i want is do a find where the result is a list of applications sorted by date and limited by 5 elements我想要的只是查找结果是按日期排序并受 5 个元素限制的applications列表

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.投影将只给出文档的所需字段,在这种情况下,如果您只想要具有_id字段的applications列表,您可以在$project中提及,如下所示在查询中,结果按应用appliedDate字段descending排序(最近的排在第一位)和有限的 5 条记录。

Assuming your collection name is test you could fire the below query to achieve the desired results:假设您的集合名称是test ,您可以触发以下查询以实现所需的结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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