【问题标题】:Mongodb aggregate $push with $cond and $eachMongodb 用 $cond 和 $each 聚合 $push
【发布时间】:2016-05-30 04:07:42
【问题描述】:

我试图在聚合$group 期间使用$cond 有条件地将$push 多个整数放到数字数组中,但没有任何成功。这是我的代码:

Item.aggregate(
    [
      {
        $group: {
          _id: "$_id",
          numbers: {
            $push: {
              $cond: { 
                if: { $gt: [ "$price.percent", 70 ] }, 
                then: { $each: [10,25,50,70] },
                else: null,
              }
            }
          }
        }
      },
    ]
  )
  ...

Mongo DB 是不是现在没有为此设置,还是我看错了?

【问题讨论】:

    标签: node.js mongodb express mongoose mongodb-query


    【解决方案1】:

    请尝试不使用$each,如下所示

    Item.aggregate(
        [{
            $group: {
              _id: "$_id",
              numbers: {
                $push: {
                  $cond: { 
                    if: { $gt: [ "$price.percent", 70 ] }, 
                    then: [10,25,50,70] ,
                    else: null,
                  }
                }
              }
            }
          }]);
    

    【讨论】:

    • 嗨@zangw,感谢您的回复!这就是我最终要做的事情,但后来我不得不做两次 $unwind 来解开我的数组数组。这是有条件地将多个项目推送到数组的唯一方法吗?
    • 是的,这就是我害怕的。哦,那也行。谢谢!我会把你标记为正确的
    【解决方案2】:

    提供的答案将起作用,但只要执行else 块,它们就会将null 添加到数组中,最后您需要从实际数组(numbers)中过滤掉null 值,即一个额外的步骤!

    您可以使用 $$REMOVE 有条件地排除 MongoDB 的 $project 中的字段。

    Item.aggregate(
        [{
            $group: {
                _id: "$_id",
                numbers: { $push: { $cond: [{ $gt: ["$price.percent", 70] }, [10, 25, 50, 70], '$$REMOVE'] } } // With $$REMOVE nothing happens on else
            }
        }]);
    

    参考: $cond

    【讨论】:

      【解决方案3】:

      你试过了吗:

      Item.aggregate(
          [
            {
              $group: {
                _id: "$_id",
                numbers: {
                  $push: {
                    $each: { 
                      $cond: { 
                        if: { $gt: [ "$price.percent", 70 ] }, 
                        then: [10,25,50,70],
                        else: null
                      }
                    }
                  }
                }
              }
            },
          ]
        )
      

      【讨论】:

        猜你喜欢
        • 2020-12-30
        • 2019-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多