【发布时间】:2017-06-14 08:46:15
【问题描述】:
我有一个如下所示的文档集合:
[
{
"_id": "588cf61e5120ac11d4366f5c",
"title": "This is a test entry",
"entrybody": "This is the body of an entry",
"creationdate": 1111,
"author": "1223cllclclclc",
"__v": 0
},
{
"_id": "588cf6a556414f02f4e6a865",
"title": "This is a new entry",
"entrybody": "This is the body of an nuew entry",
"creationdate": 11114040050505,
"author": "1223cllclclclclslslsl",
"__v": 0
},
{
"_id": "588cf767fc2ede200cd5738e",
"title": "This is a new entry",
"entrybody": "This is the body of an nuew entry",
"creationdate": 11114040050505,
"author": "1223cllclclclclslslsl",
"__v": 0
}
.....
]
我想获取每个作者的最后 n 条记录,然后按创建日期对它们进行排序,我已经查找了如何通过聚合来做到这一点,但我卡住了。
我需要集合的最后 N 个与特定键匹配的文档,例如作者,然后我必须按“创建日期”对该结果进行排序。我认为这与这个问题不同mongodb: how to get the last N records?
提前致谢。
【问题讨论】:
-
这没有回答我的问题,它显示了如何获取集合的最后 N 个文档,但与获取与特定键匹配的最后 N 个记录然后按创建日期对结果进行排序没有任何关系。
-
您只需要包含查询条件。试试
db.collection.find({"author":"somevalue"}).sort({"creationdate":-1}).limit(10); -
这将只返回一个作者的文档,我需要查询返回所有作者的最后 N 个文档。
-
对不起,我看错了。您需要为此进行聚合。
-
是的,但我坚持如何实现聚合以获得我需要的东西。