I have a collection, say, "Things":
我有一个集合,比如,“东西”:
{ id: 1
creator: 1
created: Today }
{ id: 2
creator: 2
created: Today }
{ id: 3
creator: 2
created: Yesterday }
I'd like to create a query that'll return each Thing created by a set of users, but only their most recently created thing.
我想创建一个查询,它将返回由一组用户创建的每个Thing,但只返回他们最近创建的东西。
What would this look like? I can get search my collection with an array of creators and it works just fine - how can I also only get the most recently created object per user?
这会是什么样的?我可以使用一系列创建者搜索我的集合,它可以正常工作 - 我怎样才能获得每个用户最近创建的对象?
Thing.find({ _creator : { "$in" : creatorArray })...
1 个解决方案
#1
3
You cannot find
, sort
and pick the most recent in just a single find()
query. But you can do it using aggregation:
您只能在一个find()查询中找不到,排序和选择最新的。但是你可以使用聚合来做到这一点:
-
Match
all the records where the creator is amongst the one who we are looking for. - 匹配创建者所在的所有记录。
-
Sort
the records in descending order based on the created field. - 根据创建的字段按降序对记录进行排序。
-
Group
the documents based on the creator. - 根据创建者对文档进行分组。
- Pick each creator's first document from the group, which will also be his latest.
- 从群组中挑选每个创作者的第一个文档,这也是他的最新文档。
-
Project
the required fields. - 投射必填字段。
snippet:
片段:
Thing.aggregate([
{$match:{"creator":{$in:[1,2]}}},
{$sort:{"created":-1}},
{$group:{"_id":"$creator","record":{$first:"$$ROOT"}}},
{$project:{"_id":0,
"id":"$record.id",
"creator":"$record.creator",
"created":"$record.created"}}
], function(err,data){
})
#1
3
You cannot find
, sort
and pick the most recent in just a single find()
query. But you can do it using aggregation:
您只能在一个find()查询中找不到,排序和选择最新的。但是你可以使用聚合来做到这一点:
-
Match
all the records where the creator is amongst the one who we are looking for. - 匹配创建者所在的所有记录。
-
Sort
the records in descending order based on the created field. - 根据创建的字段按降序对记录进行排序。
-
Group
the documents based on the creator. - 根据创建者对文档进行分组。
- Pick each creator's first document from the group, which will also be his latest.
- 从群组中挑选每个创作者的第一个文档,这也是他的最新文档。
-
Project
the required fields. - 投射必填字段。
snippet:
片段:
Thing.aggregate([
{$match:{"creator":{$in:[1,2]}}},
{$sort:{"created":-1}},
{$group:{"_id":"$creator","record":{$first:"$$ROOT"}}},
{$project:{"_id":0,
"id":"$record.id",
"creator":"$record.creator",
"created":"$record.created"}}
], function(err,data){
})