MongoDB中的聚合查询

时间:2017-03-15 13:30:56

标签: mongodb mongodb-query aggregation-framework

我是MongoDB的新手。我要求从一系列产品中获取特定日期的最新更新产品。     下面是我要求的JSON对象。

{
    "_id": ObjectId("10001"),
    "product": [{
        "image": "./../../../prod1.html",
        "name": "product",
        "version": 1,
        "updatedDate": "14-03-2017"
    }, {
        "image": "./../../../prod1.html",
        "name": "product",
        "version": 2,
        "updatedDate": "14-03-2017"
    }, {
        "image": "./../../../prod1.html",
        "name": "product",
        "version": 1,
        "updatedDate": "15-03-2017"
    }, {
        "image": "./../../../prod1.html",
        "name": "product",
        "version": 2,
        "updatedDate": "15-03-2017"
    }, {
        "image": "./../../../prod1.html",
        "name": "product",
        "version": 3,
        "updatedDate": "15-03-2017"
    }, {
        "image": "./../../../prod1.html",
        "name": "product",
        "version": 4,
        "updatedDate": "15-03-2017"
    }]
}, {
    "_id": ObjectId("10002"),
    "product": [{
        "image": "./../../../prod1.html",
        "name": "product",
        "version": 1,
        "updatedDate": "14-03-2017"
    }, {
        "image": "./../../../prod1.html",
        "name": "product",
        "version": 2,
        "updatedDate": "14-03-2017"
    }, {
        "image": "./../../../prod1.html",
        "name": "product",
        "version": 1,
        "updatedDate": "15-03-2017"
    }, {
        "image": "./../../../prod1.html",
        "name": "product",
        "version": 2,
        "updatedDate": "15-03-2017"
    }, {
        "image": "./../../../prod1.html",
        "name": "product",
        "version": 3,
        "updatedDate": "15-03-2017"
    }]
},
}

我需要一个查询 - 它将使用最新版本检索14-03-2017的产品。

预期结果是:

{
"_id" : ObjectId("10001"),
"product" : [
    {"image" : "./../../../prod1.html","name" : "product","version" : 4,"updatedDate":"15-03-2017"} 
]},
 {
"_id" : ObjectId("10002"),
"product" : [
    {"image" : "./../../../prod1.html","name" : "product","version" : 3,"updatedDate":"15-03-2017"} 
]}

非常感谢有人可以帮助我获得预期结果的总体功能。

1 个答案:

答案 0 :(得分:1)

使用aggregate命令,

db.collection.aggregate([{
    $unwind: "$product"
}, {
    $sort: {
        "product.updatedDate": 1
    }
}, {
    $group: {
        _id: "$_id",
        product: {
            $last: "$product"
        }
    }
}])

输出:

{
    "_id" : ObjectId("10002"),
    "product" : {
        "image" : "./../../../prod1.html",
        "name" : "product",
        "version" : 3,
        "updatedDate" : "15-03-2017"
    }
}
{
    "_id" : ObjectId("10001"),
    "product" : {
        "image" : "./../../../prod1.html",
        "name" : "product",
        "version" : 4,
        "updatedDate" : "15-03-2017"
    }
}