如何在mongodb

时间:2019-04-04 22:02:11

标签: arrays mongodb aggregation-framework projection

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

输入:[“ foo”,“ bar”,null]

输出:[“ foo”,“ bar”]

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

2 个答案:

答案 0 :(得分:1)

这可以使用$ filter

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

答案 1 :(得分:0)

解决方案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"]
                         }
                    },
                ]
            }
        }
    }
}