MongoDb 聚合匹配日期部分
MongoDb aggregate Match date part
我正在尝试执行此查询,基本上获取上午 9 点至 9 点 59 分的所有时间点:
db.DataPoints.find({$where: "new Date(this.Head.Timestamp).getHours() === 9"}, {_id: 0, 'Body.PAC.Values.1': 1})
但作为聚合查询。你不能在 match
中做 where
db.DataPoints.aggregate([{ $match : { "Head.Timestamp": { $hour: 9 } } },...
无效。到目前为止搜索一无所获。
编辑:示例文档如下:
{
"_id" : "d5c75619-fe17-4618-9333-004e3ee67cb3",
"Head" : {
"Timestamp" : ISODate("2015-05-20T04:20:00.000Z"),
"RequestArguments" : {
"Query" : "Inverter",
"Scope" : "System"
},
"Status" : {
"Code" : 0,
"Reason" : "",
"UserMessage" : ""
}
},
"Body" : {
"PAC" : {
"Unit" : "W",
"Values" : {
"1" : 55
}
},
"DAY_ENERGY" : {
"Unit" : "Wh",
"Values" : {
"1" : 24
}
},
"YEAR_ENERGY" : {
"Unit" : "Wh",
"Values" : {
"1" : 55017
}
},
"TOTAL_ENERGY" : {
"Unit" : "Wh",
"Values" : {
"1" : 119228
}
}
}
}
更好的方法是使用 $redact
pipeline which is bit nicer than using $project
for a logical condition and then using $match
to filter that logical match. It will return all documents match the condition using $$KEEP
and discards those that don't match using the $$PRUNE
变量:
db.DataPoints.aggregate([
{
"$redact": {
"$cond": {
"if": {
"$eq": [
{ "$hour" : "$Head.Timestamp" },
9
]
},
"then": "$$KEEP",
"else": "$$PRUNE"
}
}
}
])
较长的方法是使用 $project
operator that stores the hour value which you can then use in the next $match
管道创建一个新字段:
db.DataPoints.aggregate([
{
"$project" : {
"hour" : { "$hour" : "$Head.Timestamp" },
"Head": 1,
"Body": 1
}
},
{ "$match": { "hour": 9 } }
])
我正在尝试执行此查询,基本上获取上午 9 点至 9 点 59 分的所有时间点:
db.DataPoints.find({$where: "new Date(this.Head.Timestamp).getHours() === 9"}, {_id: 0, 'Body.PAC.Values.1': 1})
但作为聚合查询。你不能在 match
中做 wheredb.DataPoints.aggregate([{ $match : { "Head.Timestamp": { $hour: 9 } } },...
无效。到目前为止搜索一无所获。
编辑:示例文档如下:
{
"_id" : "d5c75619-fe17-4618-9333-004e3ee67cb3",
"Head" : {
"Timestamp" : ISODate("2015-05-20T04:20:00.000Z"),
"RequestArguments" : {
"Query" : "Inverter",
"Scope" : "System"
},
"Status" : {
"Code" : 0,
"Reason" : "",
"UserMessage" : ""
}
},
"Body" : {
"PAC" : {
"Unit" : "W",
"Values" : {
"1" : 55
}
},
"DAY_ENERGY" : {
"Unit" : "Wh",
"Values" : {
"1" : 24
}
},
"YEAR_ENERGY" : {
"Unit" : "Wh",
"Values" : {
"1" : 55017
}
},
"TOTAL_ENERGY" : {
"Unit" : "Wh",
"Values" : {
"1" : 119228
}
}
}
}
更好的方法是使用 $redact
pipeline which is bit nicer than using $project
for a logical condition and then using $match
to filter that logical match. It will return all documents match the condition using $$KEEP
and discards those that don't match using the $$PRUNE
变量:
db.DataPoints.aggregate([
{
"$redact": {
"$cond": {
"if": {
"$eq": [
{ "$hour" : "$Head.Timestamp" },
9
]
},
"then": "$$KEEP",
"else": "$$PRUNE"
}
}
}
])
较长的方法是使用 $project
operator that stores the hour value which you can then use in the next $match
管道创建一个新字段:
db.DataPoints.aggregate([
{
"$project" : {
"hour" : { "$hour" : "$Head.Timestamp" },
"Head": 1,
"Body": 1
}
},
{ "$match": { "hour": 9 } }
])