【问题标题】:mongoDB query using aggregate to query the most recent date of an itemmongoDB查询使用聚合查询项目的最近日期
【发布时间】:2016-10-13 09:59:16
【问题描述】:

我有一个这样的收藏:

[
    { 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 并没有真正的经验,有人能让我知道编写这个查询的正确(和最高效)的方法是什么吗?

【问题讨论】:

  • 你快到了,最后一个匹配过滤掉了所有结果,因为在 $group 之后:id 变成了_id: { vendor_name: 'test1' }。当心聚合管道从头到尾一个接一个地运行,顺序很重要

标签: mongodb aggregation-framework


【解决方案1】:

第一件事 :-)

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

  2. $group 中,您可以使用$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"
                }
            }
        }
    ])

【讨论】:

  • 这太棒了!谢谢。只是另一个问题,我还想返回最低 business_date 的“价格”字段,我将如何在 $group 中编写该查询?
  • 我为上面的 ^^ 创建了另一个问题。 stackoverflow.com/questions/37795662/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-18
  • 1970-01-01
  • 1970-01-01
  • 2014-08-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多