MongoDB分组求和 得到的数据包含其他字段数据

mongodb中user集合中存在如下数据:

{uid: "1","vn": "LB23","time": "2017-10-01","record": 123}
{uid: "1","vn": "LB24","time": "2017-10-03","record": 133}
{uid: "1","vn": "LB24","time": "2017-10-02","record": 123}
{uid: "1","vn": "LB24","time": "2017-10-04","record": 1222}
{uid: "1","vn": "LB25","time": "2017-10-01","record": 123}
{uid: "1","vn": "LB25","time": "2017-10-02","record": 1223}

结果是根据vn统计出最大时间数据然后在统计record的总和,但是自己在查询的时候先分组求出最大时间条数,然后在根据子文档进行求总数

 { "$group" : { "_id" : { "vn" : "$vn" } , "collect_time" : { "$max" : "$time"}}} 

通过这个命令后得到的数据集合是:

{“_id”:{"vn":"LB25"},"time":"2017-10-02"}
{“_id”:{"vn":"LB24"},"time":"2017-10-04"}
...

此处没有包含record数据,请问一下 我该如何修改呢?

阅读 2.4k
评论
    2 个回答

    这种思路下aggregation语法不好写,但是换个思路就好写了:

    db.test.insert([
        {uid: "1","vn": "LB23","time": "2017-10-01","record": 123},
        {uid: "1","vn": "LB24","time": "2017-10-03","record": 133},
        {uid: "1","vn": "LB24","time": "2017-10-02","record": 123},
        {uid: "1","vn": "LB24","time": "2017-10-04","record": 1222},
        {uid: "1","vn": "LB25","time": "2017-10-01","record": 123},
        {uid: "1","vn": "LB25","time": "2017-10-02","record": 1223}
    ])
    db.test.aggregate([
        {$sort: {vn: 1, time: -1}},
        {$group: {_id: "$vn", doc: {$first: "$$ROOT"}}},
    ])

    即:根据vntime先排好序,然后取每个独立vn的第一条数据(就是时间最大那条)。
    输出结果为(简单起见我把整个文件都取出来了,请根据需要调整):

    { "_id" : "LB25", "doc" : { "_id" : ObjectId("59ed572a70650b44dccaf986"), "uid" : "1", "vn" : "LB25", "time" : "2017-10-02", "record" : 1223 } }
    { "_id" : "LB24", "doc" : { "_id" : ObjectId("59ed572a70650b44dccaf984"), "uid" : "1", "vn" : "LB24", "time" : "2017-10-04", "record" : 1222 } }
    { "_id" : "LB23", "doc" : { "_id" : ObjectId("59ed572a70650b44dccaf981"), "uid" : "1", "vn" : "LB23", "time" : "2017-10-01", "record" : 123 } }

    适当的索引可以加快你的存取速度:

    db.test.createIndex({vn: 1, time: -1});
    评论 赞赏
      MongoDB 技术问答
      合作问答

      MongoDB 官方中文社区 和 SegmentFault 联合推出的 MongoDB 技术交流平台。 这是一个以社区力量为主,但...