mongoDB 关联查询

2019-01-23  本文已影响3人  Robin92

现在是实现一个关联查询。
由于数据库分库,每个 account 对应的分库的配置信息存在 accountDSNConfig 表中,需要关联的表为 account 表,存在关系 accountDSNConfig.accountId==account._id。我现在要把同一库(即 accountDSNConfig.dsn 相同)中的accountId统计出来,并且筛选掉未激活的account。
以下为命令实现:

db.getCollection('accountDSNConfig').aggregate([
    {
        "$lookup": {
            "from": "account", // the name of collection which to join
            "localField": "account_id", // field name in accountDSNConfig
            "foreignField": "_id", // the name of the same field value with accountDSNConfig's localField in joined collection
            "as": "account" // as a filed name in this project
        }
    },
        {"$match": {"account.isDeleted": false, "account.status": "activated"}}, // query in aggregate as usual
        {"$group": {_id: "$dsn", "accountIds": {"$push": "$accountId"}}}
])

其实关联查询重要的一个命令是 $lookup 这个命令的 stage,每个stage都相当于一个管道,详情可以看官网解释。

上一篇 下一篇

猜你喜欢

热点阅读