【问题标题】:How to remove an array element with value null in projection (project), mongodb如何在投影(项目)中删除值为null的数组元素,mongodb
【发布时间】:2019-04-04 22:02:11
【问题描述】:

我正在尝试从数组中删除一个空元素,在投影中,尝试使用 $reduce

输入:["foo", "bar", null]

输出:["foo", "bar"]

$project: {
    "newArray": { 
        $reduce: {
        input: "$arrayInput",
            initialValue: [],
            in: {
                $concatArrays: [
                    "$$value",
                     {
                         $cond: {
                             if: { $eq: [ "$$this", null ] },
                             then: [],
                             else: ["$$this"]
                         }
                    },
                ]
            }
        }
    }
}

【问题讨论】:

  • 您能否也展示样本集合以及您想要的输出

标签: arrays mongodb aggregation-framework projection


【解决方案1】:

这可以使用 $filter 来实现

$project: {
    newArray: {
        $filter: {
            input: "$arrayInput",
            as: "a",
            cond: {$ne:["$$a",null]}
            }
        }
    }

【讨论】:

    【解决方案2】:

    解决方案 1:

    我们必须将$$this转换成数组([$$this])并与[null]比较

    $project: {
        "newArray": { 
            $reduce: {
            input: "$arrayInput",
                initialValue: [],
                in: {
                    $concatArrays: [
                        "$$value",
                        {
                             $cond: {
                                 if: { $eq: [["$$this"], [null]] },
                                 then: [],
                                 else: ["$$this"]
                             }
                        },
                    ]
                }
            }
        }
    }
    

    解决方案 2:

    如果您想消除重复值,我们必须在输入值中使用 $setIntersection。

    输入:["foo", "bar", null, "foo", "bar"]

    输出:["foo", "bar"]

    $project: {
        "newArray": { 
            $reduce: {
            input: { "$setIntersection": "$arrayInput" },
                initialValue: [],
                in: {
                    $concatArrays: [
                        "$$value",
                        {
                             $cond: {
                                 if: { $eq: [["$$this"], [null]] },
                                 then: [],
                                 else: ["$$this"]
                             }
                        },
                    ]
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-24
      • 2016-03-26
      • 2020-08-31
      • 1970-01-01
      • 2018-02-20
      • 2021-12-11
      相关资源
      最近更新 更多