如何在$ lookup猫鼬中对对象数组执行嵌套条件

时间:2020-09-01 07:47:38

标签: mongodb mongoose mongoose-schema

我有两个如下文件

A = {
    _id: <MongoDb ObjectId>
    user: {
        type: ObjectId,
        ref: 'users'
    }
    .... <other property>
}

B = {
    _id: <MongoDB ObjectId>
    a: {
        type: mongoose.Schema.Types.ObjectID
        ref: 'a'
    },
    content: [
        {
            status: {
                c: String
            }
        }
    ]
}

我需要获取包括b的详细信息,其中内容可以为空白或状态。c ===对用户“完成”。 结果必须包含详细信息,如果不满足条件,则b可以为空白

我使用下面的Adapt方法,但无法获得预期的结果

A.aggregate([
    {
        $match: {$expr: { $and: [ { user: <SomeDefinedID>} ]}}
    },
    {
        $lookup: {
            from: "b",
            localField: "_id",
            foreignField: "a",
            as: 'b'
        }
    },
    {
        $unwind: "$b"
    },
    {
        $match: {$expr: { $and: [ { $eq: [ "$b.content.status.c", "done" ] } ]}}
    },
]).exec(console.log);

有时我得到了空数组,尽管我在A中有记录,但是b可以是[]或结果'c'是'done'。

0 个答案:

没有答案