mongoDB查询使用聚合查询项目的最新日期并返回最近日期的记录

时间:2016-06-13 17:21:17

标签: mongodb aggregation-framework

我有一个这样的集合:

[
    { product_name: "Orange",vendor_name: "test1", category: "Fruit",  business_date: "2015-06-12T00:00:00.000Z", "price": 2.00},
    { product_name: "Orange",vendor_name: "test1", category: "Fruit",  business_date: "2015-02-24T00:00:00.000Z", "price": 5.00}, 
    { product_name: "Apple",vendor_name: "test2", category: "Fruit",  business_date: "2015-07-11T00:00:00.000Z", "price": 3.00},
    { product_name: "Apple",vendor_name: "test2", category: "Fruit",  business_date: "2015-06-19T00:00:00.000Z", "price": 6.00} 
]

我想查询集合,以便在最近的“business_date”中查找每个项目的价格,在此示例中,它应该是记录#2,$ 5.00和记录#4,$ 6.00。我将如何继续为此编写聚合查询?这与mongoDB query using aggregate to query the most recent date of an item有关。 我在下面尝试过:

var pipeline = [
    {
        $match: {
            category: {$in: ['Fruit']}
        }
    },
    {
        $group : {
           _id : { vendor_name: "$vendor_name", product_code: "$product_code" },
           business_date: {$max: "$business_date"}, 
           price: {$last: "$price"}
        }
    } 
]
db.sales.aggregate(pipeline);

但没有得到我想要的结果。有什么建议吗?

编辑:我使用了sort函数,但是想知道这是否在逻辑上是正确的,并且是否有更好,更有效的方法来实现相同的目标?:

var pipeline = [
    {
        $match: {
            category: {$in: ['Fruit']}
        }
    },
    {
        $sort: {
            business_date: -1
        }
    },
    {
        $group : {
           _id : { vendor_name: "$vendor_name", product_code: "$product_code" },
           business_date: {$max: "$business_date"},
           price: {$first: "$price"}
        }
    } 
];

0 个答案:

没有答案