繁体   English   中英

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

[英]mongoDB query using aggregate to query the most recent date of an item and return the record that's in the most recent date

我有一个这样的收藏:

[
    { 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查询有关。 我在下面尝试过:

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"}
        }
    } 
];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM