我有一个mongo文档,其结构类似于
{
"_id" : "THIS_IS_A_DHP_USER_ID+2014-11-26",
"_class" : "weight",
"items" : [
{
"dateTime" : ISODate("2014-11-26T08:08:38.716Z"),
"value" : 98.5
},
{
"dateTime" : ISODate("2014-11-26T08:18:38.716Z"),
"value" : 95.5
},
{
"dateTime" : ISODate("2014-11-26T08:28:38.663Z"),
"value" : 90.5
}
],
"source" : "MANUAL",
"to" : ISODate("2014-11-26T08:08:38.716Z"),
"from" : ISODate("2014-11-26T08:08:38.716Z"),
"userId" : "THIS_IS_A_DHP_USER_ID",
"createdDate" : ISODate("2014-11-26T08:38:38.776Z")
}
{
"_id" : "THIS_IS_A_DHP_USER_ID+2014-11-25",
"_class" : "weight",
"items" : [
{
"dateTime" : ISODate("2014-11-25T08:08:38.716Z"),
"value" : 198.5
},
{
"dateTime" : ISODate("2014-11-25T08:18:38.716Z"),
"value" : 195.5
},
{
"dateTime" : ISODate("2014-11-25T08:28:38.716Z"),
"value" : 190.5
}
],
"source" : "MANUAL",
"to" : ISODate("2014-11-25T08:08:38.716Z"),
"from" : ISODate("2014-11-25T08:08:38.716Z"),
"userId" : "THIS_IS_A_DHP_USER_ID",
"createdDate" : ISODate("2014-11-26T08:38:38.893Z")
}
要在此文档结构上触发的查询,用于查找特定用户标识的文档,展开嵌入的数组并获取介于特定日期范围之间的对象。
是否可以为此类查询创建聚合,否则需要使用map-reduce类型的查询来解决此问题。
答案 0 :(得分:1)
您可以按以下方式汇总:
Initialize
开始日期和结束日期变量。Match
所需的userId文档。Unwind
items array。$and
运算符match
日期在范围内的项目。Group
基于userId
。Project
必填字段。代码:
var startDate = ISODate(); // initialize the correct start date
var endDate = ISODate(); // initialize the correct end date.
db.collection.aggregate([
{$match:{"userId":"THIS_IS_A_DHP_USER_ID"}},
{$unwind:"$items"},
{$match:{$and:[{"items.dateTime":{$gt:startDate}},
{"items.dateTime":{$lt:endDate}}]}},
{$group:{"_id":"$userId",
"items":{$push:"$items"},
"_class":{$first:"$_class"},
"source":{$first:"$source"},
"to":{$first:"$to"},
"from":{$first:"$from"},
"createdDate":{$first:"$createdDate"}}},
{$project:{"_id":0,
"items":1,
"_class":1,
"source":1,
"to":1,
"from":1,
"createdDate":1,"userId":"$_id"}}
])