mongoDB查询 - 消除重复结果

时间:2015-07-01 06:28:26

标签: mongodb mongodb-query

我有一个看起来像这样的集合:

{
"_id" : ObjectId("558c108b209c022c947b0055"),
"term" : "aero storm tour",
"year" : "2015",
"month" : "06",
"day" : "01",
"hour" : "17",
"dayofyear" : "184",
"weekofyear" : 26,
"productcount" : 2,
"count" : 1
}


{
"_id" : ObjectId("558c108b209c022c947b0056"),
"term" : "aero storm tour",
"year" : "2015",
"month" : "06",
"day" : "01",
"hour" : "17",
"dayofyear" : "184",
"weekofyear" : 26,
"productcount" : 2,
"count" : 2
}


{
"_id" : ObjectId("558c108b209c022c947b0026"),
"term" : "aero",
"year" : "2015",
"month" : "06",
"day" : "01",
"hour" : "17",
"dayofyear" : "184",
"weekofyear" : 26,
"productcount" : 23,
"count" : 2
}


{
"_id" : ObjectId("558c108b209c022c947b0022"),
"term" : "aero",
"year" : "2015",
"month" : "06",
"day" : "01",
"hour" : "17",
"dayofyear" : "184",
"weekofyear" : 26,
"productcount" : 23,
"count" : 12
}


{
"_id" : ObjectId("558c108b209c022c947b0032"),
"term" : "aero",
"year" : "2015",
"month" : "07",
"day" : "01",
"hour" : "17",
"dayofyear" : "184",
"weekofyear" : 26,
"productcount" : 23,
"count" : 12
}


{
"_id" : ObjectId("5348c108b09c022c947b0055"),
"term" : "aero storm tour",
"year" : "2015",
"month" : "06",
"day" : "01",
"hour" : "17",
"dayofyear" : "170",
"weekofyear" : 26,
"productcount" : 235,
"count" : 1
}


{
"_id" : ObjectId("658c108b209c022c947b0055"),
"term" : "aero storm tour",
"year" : "2015",
"month" : "06",
"day" : "01",
"hour" : "17",
"dayofyear" : "173",
"weekofyear" : 26,
"productcount" : 235,
"count" : 1
}


{
"_id" : ObjectId("558c108b209c022c947a0055"),
"term" : "aero storm tour",
"year" : "2015",
"month" : "06",
"day" : "01",
"hour" : "17",
"dayofyear" : "164",
"weekofyear" : 26,
"productcount" : 235,
"count" : 1
}

我需要找到一词,其中 productcount 在特定时小于等于2 >和

我的查询

db.tq.find( 
            { year : "2015" , month : "06" , day : "01" ,productcount: { $lte: 2 } } ,
            { _id: 0, term: 1, productcount: 1 }

          )

输出

{
"term" : "aero storm tour",
"productcount" : 2
}
{
"term" : "aero storm tour",
"productcount" : 2
}

它返回正确的结果,但我希望通过使用不同或类似的东西来避免重复的结果。

预期输出:

{
"term" : "aero storm tour",
"productcount" : 2
}

如何实现?

1 个答案:

答案 0 :(得分:2)

您的find查询无效,因为在您匹配的日期,您的收藏中有两个文档。这就是为什么它会给你两个文件。

您可以添加limit来查找查询,以便只获取一个结果,如下所示 -

db.collection.find({
    year: "2015",
    month: "06",
    day: "01",
    productcount: {
        $lte: 2
    }
    }, {
    _id: 0,
    term: 1,
    productcount: 1
    }
).limit(1)

,否则

您可以使用mongo aggregation获得预期结果,如下所示:

db.collection.aggregate({
    $match: {
    productcount: {
        $lte: 2
    },
    year: "2015",
    month: "06",
    day: "01"
    }
}, {
    $group: {
    _id: "$term",
    "term": {
        $first: "$term"
    },
    "productcount": {
        $first: "$productcount" //u can add $max:"$productcount" to get productcount with max value instead of $first: "$productcount"
    }
    }
}, {
    $project: {
    "term": 1,
    "productcount": 1,
    "_id": 0
    }
})