使用聚合查询项目的最新日期的mongoDB查询 [英] mongoDB query using aggregate to query the most recent date of an item

查看:118
本文介绍了使用聚合查询项目的最新日期的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,在此示例中,它应为记录#2 记录#4

I want to query the collection to find each item's most recent "business_date", and in this example it should be record #2, and record #4.

我将如何为此写一个汇总查询?

How would I go ahead and write an aggregate query for this?

我已经尝试过:

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并没有真正的经验,有人会让我知道编写此查询的正确方法(最有效的操作方式)吗?

But I get nothing returned. I am not really experienced with MongoDB, would somebody let me know what should be the correct( and most operation efficient) way to write this query?

推荐答案

第一件事:-)


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

  1. use $match as a first pipeline in query to increase processing speed (less data to process)

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

in $group you can use $min - no sort needed speed :-)

所以查询看起来像这样:

So query will look like this:

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

这篇关于使用聚合查询项目的最新日期的mongoDB查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆