返回唯一的mongo文档

时间:2017-03-04 10:18:17

标签: java mongodb mongodb-query aggregation-framework

我有一个收藏品。以下是样本文件

{
"bannerUserSessionId" : "565269c7d52ece855050b3b7bd4ae8d6f52161871394e2d312c340a086f93314",
"bannerId" : "<String> kitchen-chimneys||1488286849020|HP|PromoBanner4",
"bannerEventLabel" : "<String> kitchen-chimneys",
"bannerPage" : "HP",
"bannerWidget" : "PromoBanner4",
"bannerClickTimestamp" : "Mar 04, 2017 15:05:56 PM"
}
{
"bannerUserSessionId" : "565269c7d52ece855050b3b7bd4ae8d6f52161871394e2d312c340a086f93314",
"bannerId" : "<String> kitchen-   chimneys||1488286849020|HP|PromoBanner4",
"bannerEventLabel" : "<String> kitchen-chimneys",
"bannerPage" : "HP",
"bannerWidget" : "PromoBanner4",
"bannerClickTimestamp" : "Mar 04, 2017 15:06:19 PM"
}

是否可以以这样的方式查询mongodb,以便我获得唯一的文档,因为上面两个文档是相同的,除了不同的时间戳对象?

所以我只想要一张唱片。

1 个答案:

答案 0 :(得分:2)

您可以按键$group并选择$first时间戳值。

db.collection.aggregate([{
    $group: {
        _id: {
            "bannerUserSessionId": "$bannerUserSessionId",
            "bannerId": "$bannerId",
            "bannerEventLabel": "$bannerEventLabel",
            "bannerPage": "$bannerPage"
        },
        "bannerClickTimestamp": {
            $first: "$bannerClickTimestamp"
        }
    }
}])