提问者:小点点

如何在mongoDB中按key筛选,按日期范围查找,然后按周聚合?


我有一个名为MyCollection的mongo集合,其中包含如下文档:

{ 
    "_id" : ObjectId("58085384e4b0f70605461e3f"), 
    "uid" : "fa1aeafc-18db-41a5-8ee5-ac0c32428fe1",
    "Key1" : "Value1"  
    "timeStamp" : ISODate("2016-08-23T17:58:20.000+0000"), 
}

一些文档有Key1,而另一些有Key2Key3

现在,我希望做到以下几点:-

  1. 仅获取具有Key1Key2的文档。
  2. 从上面生成的文档集中,仅获取timeStamp范围Date(2016,08,01)Date(2016,08,31)中的那些文档。
  3. 对于上面生成的文档集,按周聚合它们。

如何为此编写mongo查询?


共2个答案

匿名用户

使用聚合框架,可以通过$match$group管道步骤完成上述步骤,如下所示:

var start = new Date(2016, 7, 1), // months are zero-based indexes i.e Aug month index is 7
    end = new Date(2016, 7, 30); // August month ends on the 30th

db.collection.aggregate([
    { /* filter steps 1 & 2 */
        "$match": {
            "$or": [
                { "Key1": { "$exists": true } },
                { "Key2": { "$exists": true } }
            ],
            "timeStamp": { "$gte": start, "$lte": end }
        }
    },
    { /* group by week */ 
        "$group": {
            "_id": { "$week": "$timeStamp" },
            "count": { "$sum": 1 },
            "uids": { "$push": "$uid" }
        }
    }
])

在上面,日期范围是使用Date()构造函数创建的,其中月是从零开始的索引。$存在运算符用于确定键的存在,并使用$周日期聚合运算符获取0(一年中第一个星期之前的部分周)和53(闰年)之间日期的周数。

对于从1开始的周数,其中包含一年的第一个星期四(周一到周日),MongoDB 3.4和更新版本提供了$isoweek运算符供使用。

匿名用户

试试这个:

db.collection.find(
{$or:[{"key1":{$exists:true}},{"key2":{$exists:true}}],
timeStamp: {$gte: Date(2016, 08, 01), $lte:Date(2016, 08, 31)}
})

上面的查询满足了你的1和2条件。你的第三个条件是什么,我不太明白,请详细说明。