mongodb $cond with $arrayElemAt as false condition inside aggregation

huangapple go评论74阅读模式
英文:

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告诉我:
mongodb $cond with $arrayElemAt as false condition inside aggregation

我找不到与我的情况相关的在线信息。如何在$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:
mongodb $cond with $arrayElemAt as false condition inside aggregation

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 ] }
        ]
      }
    }
  }
])

huangapple
  • 本文由 发表于 2023年7月3日 23:00:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76605933.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定