我在mongodb:中有集合,存储为:
{"tag":"count1","value":100,"ts":1544423706} {"tag":"count2","value":1002,"ts":1544423706} {"tag":"count1","value":101,"ts":1544423806} {"tag":"count2","value":1003,"ts":1544423806} {"tag":"count1","value":102,"ts":1544423906} {"tag":"count2","value":1004,"ts":1544423906}
所以我的问题是如何从“标签”中获取结果为count1,“ ts”大于1544423800的第一项。如我所愿:我想找到的结果是:
{"tag":"count1","value":101,"ts":1544423806} {"tag":"count2","value":1003,"ts":1544423806}
我是否需要使用聚合将标签分组,然后获得比给定的“ ts”大的第一项,所以我是MongoDB中聚合功能的新手。
db.index.aggregate([{"$match": {"tag": {"$in":["count1","count2"]},"ts": {"$gt":1544423800}}
},
{"$group": {"_id": "$tag",
"tags": {"$push": "$$ROOT"}}
},
])
结果不是每个标签都有一项,所以我想限制一项,我该怎么做
谢谢,我已通过以下方式解决了此问题:
db.index.aggregate(
[
{"$match": {"tag": {"$in":["count1","count2"]},
"ts": {"$gt":1545730000}}
},
{"$group": {"_id": "$tag",
"value": {"$first": "$value"}
}
},
]
)