【发布时间】:2015-10-29 11:22:59
【问题描述】:
我正在使用 aggregation 和 project 和 cond。像这样的...
假定文件为:
{outter:{
inner1:"blah",
innerOther:"somethingelse"
}}
聚合:
db.collection.aggregate([{
$project : {
"outter.inner1":1,
"outter.inner2":{
$cond : if:{"outter.innerOther":{$exists:true}},
then:{"blah":"blah"},
else:{"blah":"blah"}
}
}
}])
当我运行它时,我收到一个错误:exception: dotted field names are only allowed at the top level on the if 条件语句(我尝试将 if 替换为 if:true 并且聚合有效)。
这是一个错误吗?是否有一种解决方法,无需执行整个其他项目来简单地获得没有点的字段?
编辑
所以我找到了一种解决方法,但仍然想看看这是否是预期的行为。解决方法是通过$let 在投影中使用变量。此外,$exists 似乎不是有效的expression,因此还必须进行以下更改。
db.collection.aggregate([{
$project : {
"outter.inner1":1,
"outter.inner2":{
$let :{
vars:{innerOther:{$ifNull:["$outter.innerOther", "absent"]}},
}
$cond : if:{$eq:["$$innerOther","absent"]},
then:{"blah":"blah"},
else:{"blah":"blah"}
}
}
}])
【问题讨论】:
-
“外部”是一个数组吗?请问你能出示你的文件吗?
-
外部是子文档。
标签: mongodb mongodb-query aggregation-framework projection