【发布时间】:2017-07-01 10:28:20
【问题描述】:
我想按时间戳对文档进行排序并获得不同的孩子姓名。所以查询的预期是这样的;
[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" ] }
那么在按时间戳对孩子进行排序时,我如何才能获得最后更改的不同孩子的姓名。
【问题讨论】: