您好我需要查询来执行每小时嵌套对象的过滤器。这可以在聚合框架中。由于“小时”字段等于某个数字。我只想在每小时内返回该数字对象。我尝试了一切,有人知道对此的查询吗?
{
"_id" : "08062017/cpu",
"hour": 1
"hourly" : {
"0" : "0",
"1" : "1",
"2" : "2"
}
}
{
"_id" : "08062017/cpu2",
"hour": 2
"hourly" : {
"0" : "0",
"1" : "1",
"2" : "2"
}
}
结果:
{
"_id" : "08062017/cpu",
"hour": 1
"hourly" : {
"1" : "1"
}
}
{
"_id" : "08062017/cpu2",
"hour": 2
"hourly" : {
"2" : "2"
}
}
答案 0 :(得分:0)
如果您为每小时对象提供了不动产名称或将其展平,则以下代码将起作用。
在聚合函数中运行项目:
$project: {
hourly: {
"$let": {
"vars": {
"field": {
"$arrayElemAt": [{
"$filter": {
input: "$hourly",
as: "h",
cond: { $eq: ['$$h', '$hour'] } //hour is your property on the base document, h is your variable for the hourly array
}
}, 0]
}
},
"in": "$$field"
},
},
}
您当前的问题是hourly
数组是一组没有一致字段的对象,可以用ex:"0":"0"
映射,这应该是一个扁平数组,如下所示:
hourly: ["0", "1", "2"]
或像这样的适当对象:
hourly: [{"Zero": "0"}, {"One": "1"}]