首页 > 解决方案 > 如何对嵌套数组中的属性值执行 $lookup?

问题描述

我有一个articles包含一个数组的集合,comments这个数组包含一个数组sub_comments。这是它的样子:

let articleSchema = mongoose.Schema({
    title: {type: String},
    comments: [{
        comment: {type: String},
        creator: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'User'
        },
        sub_comments: [{
            comment: {type: String},
            creator: {
                type: mongoose.Schema.Types.ObjectId,
                ref: 'User'
            }
        }]
    }]
});

我正在尝试运行一个对and字段执行 a 的aggregate查询。这是我到目前为止尝试过的,但它不起作用:$lookupcomments.creatorsub_comments.creator

this.model('Article')
    .aggregate([
        {
            $match: {_id: article_id}
        },
        {
            $lookup: {
                from: "users",
                localField: "comments.creator",
                foreignField: "_id",
                as: "comments.creator"
            }
        },
        {
            $unwind: {
                path: "$comments.creator",
                preserveNullAndEmptyArrays: true
            }
        },
        {
            $lookup: {
                from: "users",
                localField: "comments.sub_comments.creator",
                foreignField: "_id",
                as: "comments.sub_comments.creator"
            }
        },
        {
            $unwind: {
                path: "$comments.sub_comments.creator",
                preserveNullAndEmptyArrays: true
            }
        },
        {
            $project: {
                _id: 1,
                title: 1,
                "comments.comment": 1,
                "comments.creator._id": 1,
                "comments.creator.name": 1,
                "comments.sub_comments.comment": 1,
                "comments.sub_comments.creator._id": 1,
                "comments.sub_comments.creator.name": 1
            }
        }
    ])
    .exec(function (err, data) {
        ...
    });

data这是响应的示例:

[{
"_id": "5b7e1629d00a170018e11234",
"article": "My Article",
"comments": {
        "comment": "This is the comment.",
    "sub_comments": {},
    "creator": {
    "_id": "541g2dfeab1e470b00411234",
    "name": "John Doe"
    }
},
    ....
}]

注释应该是一个数组,而不是一个对象。这个特定的评论没有任何子评论,但显然,我也希望它能够工作。关于如何让它发挥作用的任何想法?

标签: mongodbmongoose

解决方案


带有查询的 as paramsmongodb $lookup会影响您的结果。

as 指定要添加到输入文档的新数组字段的名称。新的数组字段包含来自 from 集合的匹配文档。如果输入文档中已经存在指定的名称,则覆盖现有字段。

它将覆盖归档的 . 不添加它。如果您的外部是一个数组,它将使其成为对象并删除当前内容。
所以第二个 $lookup 总计不起作用。在您的查询中

如果你想保持当前的数据结构 intac 。你可以 as a new fieldname和使用$project 来改变格式。


推荐阅读