根据条件减少 mongodb 聚合

Reduce mongodb aggregation with condition

我有一个名为“extra”的对象数组,它们具有不同的属性:有些对象有“plus”,有些没有。 我想在这个“额外”数组中创建 2 个不同的数组,一个称为“廉价”,包含所有没有“加号”属性 的对象,另一个称为“exp”,仅包含带有“加上”属性。 我想我可以在 mongodb 中使用 $reduce 方法与 $concatArrays 聚合,并用 $cond 检查 属性 plus 是否存在。 类似的东西:

数据示例:

{
    extra: [
        {
            description: "laces",
            type: "exterior",
            plus: '200'
        },
        {
            description: "sole",
            type: "interior"
        },
        {
            description: "logo",
            type: "exterior"
        },
        {
            description: "stud",
            type: "exterior",
            plus: '450'
        }
    ],
}
 {
    $project: {
        extra: {
            $reduce: {
                input: ['$extra'],
                initialValue: {cheap: [], exp: []},
                $cond: {
                    if: {$eq: ['$$this.plus', null]},
                    then: {
                        in: {
                            cheap: {
                                $concatArrays: ['$$value.cheap', '$$this'],
                            },
                        },
                    },
                    else: {
                        in: {
                            exp: {
                                $concatArrays: ['$$value.exp', '$$this'],
                            },
                        },
                    },
                },
            },
        },
    },
}    

它不起作用...我尝试了很多方法或编写了 $cond 部分但没有成功。 我想不通。 谢谢你们。 K.

除了一些小的语法问题,您还有另一个问题是您对 $ne 运算符的理解。

在这种情况下,您希望缺失值等于 null,这不是 Mongo 的工作方式。所以对于文档:

{ name: "my name" }

聚合查询:

{ $cond: { $eq: ["$missingField", null] } }

不会像您期望的那样给出 true,因为 missing 不等于 null。我冒昧地修复了您遇到的语法问题,这个工作管道是要走的路:

db.collection.aggregate([
  {
    $project: {
      extra: {
        $reduce: {
          input: "$extra",
          initialValue: {
            cheap: [],
            exp: []
          },
          in: {
            cheap: {
              "$concatArrays": [
                "$$value.cheap",
                {
                  $cond: [
                    "$$this.plus",
                    [],
                    [
                      "$$this"
                    ],
                    
                  ]
                }
              ]
            },
            exp: {
              "$concatArrays": [
                "$$value.exp",
                {
                  $cond: [
                    "$$this.plus",
                    [
                      "$$this"
                    ],
                    []
                  ]
                }
              ]
            }
          }
        },
        
      },
      
    },
    
  }
])

Mongo Playground

需要注意的一件事是 $cond 评估 plus 字段,这意味着如果该字段确实存在 null 值或 0 值,那么它将考虑此文档与 cheap 数组匹配。如果可能的话,这是需要考虑和改变的事情。