当MongoDB聚合找不到任何结果时,它将返回带有空对象的数组

时间:2018-08-15 08:47:24

标签: mongodb aggregation-framework

我想在项目汇总中获取单个项目的投标清单。

但是当我运行Mongodb聚合时,如果找不到项目投标的任何结果,它将返回以下结果:

[ { _id: 5b69f6afa1ad1827cc9e1dc6,
    projectID: 100029,
    bidsArray: [ { freelanceArray: {} } ]
} ]

但是,如果找不到相关的出价,我想返回空的 bidsArray (这样):

[ { _id: 5b69f6afa1ad1827cc9e1dc6,
    projectID: 100029,
    bidsArray: []
} ]

这是我的总数:

[
        {
            $match: {
                projectID: projectID
            }
        },
        {
            $lookup: {
                from: "bids",
                localField: "projectID",
                foreignField: "projectID",
                as: "bidsArray"
            }
        },
        {
            $unwind: {
                path: "$bidsArray",
                preserveNullAndEmptyArrays: true
            }
        },
        {
            $lookup: {
                from: "users",
                localField: "bidsArray.freelanceID",
                foreignField: "userID",
                as: "freelanceArray"
            }
        },
        {
            $unwind: {
                path: "$freelanceArray",
                preserveNullAndEmptyArrays: true
            }
        },
        {
            $group: {
                _id: "$_id",
                projectID: { $first: "$projectID" },
                bidsArray: {
                    $addToSet: {
                        bidID: "$bidsArray.bidID",
                        daysToDone: "$bidsArray.daysToDone",
                        freelanceArray: {
                            userID: "$freelanceArray.userID",
                            username: "$freelanceArray.username",
                            publicName: "$freelanceArray.publicName",
                        }
                    }
                }
            }
        },
        {
            $project: {
                projectID: 1,
                bidsArray: {
                    bidID: 1,
                    daysToDone: 1,
                    freelanceArray: {
                        userID: 1,
                        username: 1,
                        publicName: 1,
                    }
                }
            }
        }
    ]

1 个答案:

答案 0 :(得分:1)

在MongoDB 3.6中,可以在聚合表达式中使用变量$$REMOVE来有条件地禁止显示字段。

删除最后一个$project阶段,并更新$group内的freelanceArray表达式,如下所示。 $cond表达式基本上检查freelanceArray的值(不是null值)在输出字段时检查,否则删除freelanceArray。

V/hello: retrofit.client.UrlConnectionClient$TypedInputStream@77dfecd