2017-03-15 280 views
0

我是MongoDB的新手。我有要求從一系列產品中獲取特定日期的最新更新產品。 下面是我的需求的JSON對象。MongoDB中的聚合查詢

{ 
    "_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"} 
]} 

這將是高度讚賞有人能幫助我與聚合函數來獲得預期的結果。

+0

需要取得與最新的日期和最新版本的產品在該日期(日期將包含多個版本) – yuvan

+0

什麼是你的MongoDB服務器版? – chridam

回答

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" 
    } 
} 
+0

你好朋友,非常感謝。它工作完美。感謝您的直接回復。 – yuvan