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数据,请问一下 我该如何修改呢?
这种思路下
aggregation
语法不好写,但是换个思路就好写了:即:根据
vn
和time
先排好序,然后取每个独立vn
的第一条数据(就是时间最大那条)。输出结果为(简单起见我把整个文件都取出来了,请根据需要调整):
适当的索引可以加快你的存取速度: