2017-02-13 88 views
0

我想通过时间戳对文档进行排序并获取不同的子级名称。所以对查询的期望是类似的;

[alex, elizabeth, felix, tom, sonny, ashton, sharon] 

收集是;

{ "timestamp" : 1486641003000, children: [{name: "sharon"}] }, 
{ "timestamp" : 1486645481504, children: [{name: "tom"} , {name: "alex"}]}, 
{ "timestamp" : 1486732863102, children: [{name: "alex"}, {name: "elizabeth"}] }, 
{ "timestamp" : 1486642403974, children: [{name: "sonny"}] }, 
{ "timestamp" : 1486641003000, children: [{name: "elizabeth"}] }, 
{ "timestamp" : 1486645481504, children: [{name: "felix"}] }, 
{ "timestamp" : 1486645481504, children: [{name: "tom"} , {name: "alex"}]}, 
{ "timestamp" : 1486642623178, children: [{name: "alex"}] }, 
{ "timestamp" : 1486642403974, children: [{name: "felix"}] }, 
{ "timestamp" : 1486641003000, children: [{name: "ashton"}] }, 

到目前为止我做了什么?

db.collection.aggregate([ 
    {$unwind: "$children"}, 
    {$sort: {"timestamp" : -1}}, 
    {$group: {"_id" : "" , children: {$addToSet: "$children.name"}}} 
]) 

但我认为分组根据时间戳覆盖排序。因为结果不像我所期望的那样;

{ "_id" : "", "children" : [ "ashton", "felix", "tom", "sonny", "elizabeth", "sharon", "alex" ] } 

那么我怎样才能得到最后更改不同的儿童的名字,同时按时间戳排序。

回答

1

所以你将不得不在这种情况下排序和分组一次。

db.collection.aggregate([ 
    {$unwind: "$children"}, 
    {$sort: { "timestamp": -1 }}, 
    {$group: {"_id": "$children.name", "timestamp": {$first: "$timestamp"}}}, 
    {$sort: { "timestamp": -1 }}, 
    {$group: {"_id": null, "children": {$push: "$_id"}}} 
]) 

结果将如下所示:

{ "_id" : null, "children" : [ "alex", "elizabeth", "tom", "felix", "sonny", "sharon", "ashton" ] } 

这是因为“汤姆”和“费利克斯”有相似的时间戳,同为“沙龙”和“阿什顿”。