mongoDB查询使用聚合来查询项目的最近日期

时间:2016-06-13 04:52:56

标签: mongodb aggregation-framework

我有一个这样的集合:

[
    { 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 #2record #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没有多少经验,有人会让我知道编写这个查询的正确(以及最有效的操作)方法是什么?

1 个答案:

答案 0 :(得分:1)

首先要做的事情: - )

  1. 使用$match作为查询中的第一个管道,以提高处理速度(减少要处理的数据)

  2. $group {li>

    您可以使用$min - 无需排序 速度 : - )

    所以查询将如下所示:

    db.wab.aggregate([{
                $match : {
                    vendor_name : {
                        $in : ["test1", "test2"]
                    },
                    category : 'Fruit'
                }
            }, {
                $group : {
                    _id : {
                        vendor_name : "$vendor_name",
                        product_name : "$product_name"
                    },
                    business_date : {
                        $min : "$business_date"
                    }
                }
            }
        ])
    
相关问题