英文:
mongodb $cond with $arrayElemAt as false condition inside aggregation
问题
我在$project步骤内。
{
'res': {$cond: [
{$or: [{$lte: ['$list', null]}, {$eq: ['$list', []]}]},
'$root_field',
{$arrayElemAt: ['$list.obj.field', 0]}
]}
}
我想要检查根列表是否为null或空。如果是,我想要取另一个根字段,否则我需要取列表对象值的第一个元素。但这段代码写得不好,因为Compass告诉我:
我找不到与我的情况相关的在线信息。如何在$cond内部处理$arrayElemAt?我想这可能是问题所在。
英文:
I'm inside the $project step.
{
'res' : {$cond: [
{$or: [{'$lte' :['$list', null]},
{$eq: ['$list', []]}]
},
'$root_field',
{'$arrayElemAt':
['$list.obj.field',
0]]}}
}
I want to check if a root list is null or empty. If it is, I want to take another root field, otherwise I need to take the first element of the list's object's value. But this is not written well, as compass tells me:
I cannot find anything online relative to my case. How to manage the $arrayElemAt inside the $cond? I suppose that's the problem here
答案1
得分: 1
你缺少了闭合括号:
db.collection.aggregate([
{
$set: {
res: {
$cond: [
{
$or: [
{ $lte: [ "$list", null ] },
{ $eq: [ "$list", [] ] }
]
},
"$root_field",
{ $arrayElemAt: [ "$list.obj.field", 0 ] }
]
}
}
}
])
英文:
You misplaced on closing brackte:
db.collection.aggregate([
{
$set: {
res: {
$cond: [
{
$or: [
{ $lte: [ "$list", null ] },
{ $eq: [ "$list", [] ] }
]
},
"$root_field",
{ $arrayElemAt: [ "$list.obj.field", 0 ] }
]
}
}
}
])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论