【问题标题】:$group and timestamp $sort mongodb$group 和时间戳 $sort mongodb
【发布时间】: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" ] }

那么在按时间戳对孩子进行排序时,我如何才能获得最后更改的不同孩子的姓名。

【问题讨论】:

    标签: mongodb sorting grouping


    【解决方案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”的时间戳相似,与“sharon”和“ashton”相同。

    【讨论】:

      猜你喜欢
      • 2017-03-16
      • 2012-10-01
      • 2017-07-04
      • 1970-01-01
      • 2015-11-09
      • 2017-11-08
      • 2012-02-18
      • 1970-01-01
      相关资源
      最近更新 更多