我有一个名为MyCollection
的mongo集合,其中包含如下文档:
{
"_id" : ObjectId("58085384e4b0f70605461e3f"),
"uid" : "fa1aeafc-18db-41a5-8ee5-ac0c32428fe1",
"Key1" : "Value1"
"timeStamp" : ISODate("2016-08-23T17:58:20.000+0000"),
}
一些文档有Key1
,而另一些有Key2
或Key3
。
现在,我希望做到以下几点:-
Key1
或Key2
的文档。timeStamp
范围Date(2016,08,01)
到Date(2016,08,31)
中的那些文档。如何为此编写mongo查询?
使用聚合框架,可以通过$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条件。你的第三个条件是什么,我不太明白,请详细说明。