$ group和timestamp $ sort mongodb

时间:2017-02-13 12:25:37

标签: mongodb sorting grouping

我希望按时间戳对文档进行排序,并获取不同的子名称。所以查询的期望就像是;

[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 个答案:

答案 0 :(得分: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" ] }

它是因为" tom"和" felix"具有相同的时间戳,与#34; sharon"相同和" ashton"。