MongoDB在外键上聚合两个集合

时间:2017-08-08 16:11:13

标签: mongodb mongoose

我正在尝试从我的Mongo实例中提取数据,该数据将显示给定帐户ID的所有用户。用户可以是多个帐户的一部分,因此我目前为Mongo模型提供了这种结构:

的usermodel:

username: {
        type: String,
        required: true,
        unique: true,
        lowercase: true
    },
    name: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        unique: true
    },

UsersToAccountModel:

{
    user: {
        type: Schema.Types.ObjectId,
        ref: 'users'
    },
    userGroup: {
        type: Schema.Types.ObjectId,
        ref: 'userGroups'
    },
    account: {
        type: Schema.Types.ObjectId,
        ref: 'accounts'
    },
    default: {
        type: Boolean,
        default: null
    }
}

UsersToAccount模型集合在其字段中保存user,account和userGroup的ObjectId,因此它充当链接集合。

对于与UsersToAccount集合中的给定帐户ID匹配的每个userId,我想获取该ID并查询users表并将其返回。在MYSQL中,查询将是:

SELECT * FROM userToAccounts u2a LEFT JOIN users u ON u.id = u2a.userId WHERE u2a.account = $ accountId

任何人都可以在这里帮助我吗?我已经厌倦聚合但我没有走得太远。

到目前为止,我的尝试无效:

const users = await this.userToAccountModel.aggregate(
                {
                    $match:  { account: requestVars.account },
                },
                {
                    $lookup : { from: "users", localField: "_id", as: "userData", foreignField: "user"}
                }
            );

由于

1 个答案:

答案 0 :(得分:0)

首先,$lookup阶段具有以下语法:

{
    $lookup: {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
    }
}

所以我认为您需要交换localFieldforeignField值。

其次,aggregate()期待一个数组。

const users = await this.userToAccountModel.aggregate([
    {
        $match:  { account: requestVars.account },
    },
    {
        $lookup : { from: "users", localField: "user", foreignField: "_id", as: "userData" }
    }
]);