查找在特定日期有效的文档

时间:2013-03-08 05:03:48

标签: mongodb date mapreduce aggregation-framework

我有一些存储在mongodb集合中的数据类似于:

{"_id": 1, "category": "food", "name": "chips", "price": 1.50, "effectiveDate": ISODate("2013-03-01T07:00:00Z")} 
{"_id": 2, "category": "food", "name": "chips", "price": 1.75, "effectiveDate": ISODate("2013-03-05T07:00:00Z")}
{"_id": 3, "category": "food", "name": "chips", "price": 1.90, "effectiveDate": ISODate("2013-03-10T07:00:00Z")}
{"_id": 4, "category": "beverage", "name": "pop", "price": 2.00, "effectiveDate": ISODate("2013-03-01T07:00:00Z")}
{"_id": 5, "category": "beverage", "name": "pop", "price": 2.25, "effectiveDate": ISODate("2013-03-05T07:00:00Z")}
{"_id": 6, "category": "beverage", "name": "pop", "price": 1.80, "effectiveDate": ISODate("2013-03-10T07:00:00Z")}

在mongodb中,我如何编写一个查询,该查询将返回按类别分组的特定日期活动的文档?

如果我在2013年3月6日指定,我希望看到结果:

{"_id": 2, "category": "food", "name": "chips", "price": 1.75, "effectiveDate": ISODate("2013-03-05T07:00:00Z")}
{"_id": 5, "category": "beverage", "name": "pop", "price": 2.25, "effectiveDate": ISODate("2013-03-05T07:00:00Z")}

我是mongo的新手,并且一直试图使用group,aggregate和mapreduce来做这件事,但是他们只是在圈子里旋转。

1 个答案:

答案 0 :(得分:1)

为了给您一个真正好的答案,我需要您的代码的更多详细信息以及您要做的事情。但如果我理解正确,我认为你可以只使用聚合框架来解决这个问题。您应该知道聚合框架使用管道概念,换句话说,每个步骤的结果都用作以下条目。

我的查询:     

db.yourcollection.aggregate([

    /* First exclude everything that is superior to a given date */
    {$match:{effectiveDate:{$lte:new Date(2013,2,6)}}},

    /* Sort the rest by date, descending */
    {$sort:{effectiveDate:-1}},

    /* Group by name+category and grab only the first result
       (the newest below that date) */
    {$group:{_id:{name:'$name',category:'$category'}, effectiveDate:{$first:"$effectiveDate"},price:{$first:"$price"}}},

    /* You said you want the results grouped by category.
       This last $group does that and returns all matching products inside an array
       It also removes the duplicates */
    {$group:{_id:'$_id.category',products:{$addToSet:{name:"$_id.name",price:"$price",effectiveDate:"$effectiveDate"}}}}

])

输出如下:

{
    "result": [
        {
            "_id": "food",
            "products": [
                {
                    "name" : "chips",
                    "price" : 1.75,
                    "effectiveDate" : ISODate("2013-03-05T07:00:00Z")
                }
            ]
        },
        {
            "_id" : "beverage",
            "products": [
                {
                    "name" : "pop",
                    "price" : 2.25,
                    "effectiveDate" : ISODate("2013-03-05T07:00:00Z")
                }
            ]
        }
    ],
    "ok":1
}

您可以更改修改上一个$group或使用$project

的最终输出