的日期我有這樣一個集合:MongoDB的查詢,查詢最近的一個項目
[
{ product_name: "Orange",vendor_name: "test1", category: "Fruit", business_date: "2015-06-12T00:00:00.000Z"},
{ product_name: "Orange",vendor_name: "test1", category: "Fruit", business_date: "2015-02-24T00:00:00.000Z"},
{ product_name: "Apple",vendor_name: "test2", category: "Fruit", business_date: "2015-07-11T00:00:00.000Z"},
{ product_name: "Apple",vendor_name: "test2", category: "Fruit", business_date: "2015-06-19T00:00:00.000Z"}
]
我要查詢的集合,即可找出每個項目的最新「business_date」,而在這個例子中它應該是record #2
和record #4
。
我將如何繼續併爲此編寫一個aggregate
查詢?
我已經試過這樣:
var pipeline = [
{
$sort: {
business_date: -1
}
},
{
$group : {
_id : { vendor_name: "$vendor_name", product_code: "$product_code" },
business_date: {$first: "$business_date"}
}
},
{
$match: {
vendor_name: {$in: ["test1", "test2"]},
category: 'Fruit'
}
}
]
db.sales.aggregate(pipeline);
但我什麼也沒得到恢復。我對MongoDB並不是很有經驗,有人會讓我知道什麼應該是寫這個查詢的正確的(也是最有效的)方法嗎?
您是幾乎沒有的最後一場比賽中過濾所有的結果,因爲在$組後:標識變成'_id:{VENDOR_NAME:「TEST1」}'。請注意集成管道從頭到尾依次運行,並且順序很重要 – somallg
聚合管道文檔https://docs.mongodb.com/manual/core/aggregation-pipeline/#aggregation-pipeline – Leo