具有多个相互关联的集合的MongoDB聚合

时间:2018-07-24 06:56:19

标签: mongodb

我有以下收藏;

users, user_roles, market_managers,  program_markets, programs

我可以以CSV格式从mongoDB导出数据并构建关系表,然后运行以下SQL语句来检索所需的数据;

select u.name, ur.type, pm.code, p.program_name, p.shortnam, p.enddate, p.description
from users u, user_roles ur, market_managers mm, program_markets pm, programs p
where u.roles_0 = ur.id
and ur.type = 'CountryManager' 
and u.id = mm.userid
and pm.programid = mm.programid
and pm.id = mm.marketid
and p.id = pm.programid;

如何通过编写本机mongo语法获得相同的结果?

以下是作用域中的集合列表:

用户集合

{ 
    "_id" : ObjectId("5b3f59c96e1c20d84e2b5ce5"), 
    "name" : "some_country_manager",
    "roles" : [
        "5b2a8df52b3a6f945d4e85fe"
    ]
}

user_roles集合

{ 
    "_id" : ObjectId("5b430f9981f6a7382a24995b"), 
    "type" : "countryManager", 
    "name" : "Country Manager"
}

market_managers集合

{ 
    "_id" : ObjectId("5894bcf60418700b70745fc9"), 
    "programId" : "5862c1d43b1a1b113a8a841f", 
    "marketId" : "5862c1d43b1a1b113a8a84a9", 
    "userId" : "5b3f59c96e1c20d84e2b5ce5"
}

program_markets集合

{ 
    "_id" : ObjectId("5b43588689c117241c171e8c"), 
    "code" : "de", 
    "startDate" : "2018-07-09", 
    "endDate" : "2019-07-09"
}

程序集合

{ 
    "_id" : ObjectId("5862c1d43b1a1b113a8a841f"), 
    "name" : "Test Program", 
    "shortname" : "TestP", 
    "status" : "planned", 
    "startDate" : "2018-07-09", 
    "endDate" : "2019-07-09", 
    "description" : "Test Program"
}

1 个答案:

答案 0 :(得分:1)

如果您拥有mongodb 3.6及更高版本,则可以尝试以下聚合

Users.aggregate([
  { "$match": { "_id": mongoose.Types.ObjectId(id.id) } },
  { "$lookup": {
    "from": UserRoles.collection.name,
    "let": { "roles_0": "$roles_0" },
    "pipeline": [
      { "$match": {
        "$expr": { "$eq": [ "$_id", "$$roles_0" ] },
        "type": "CountryManager"
      }}
    ],
    "as": "role"
  }},
  { "$lookup": {
    "from": MarketManagers.collection.name,
    "let": { "user_id": "$_id" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": [ "$_id", "$$user_id" ] }}},
      { "$lookup": {
        "from": Programs.collection.name,
        "let": { "programid": "$programid" },
        "pipeline": [
          { "$match": { "$expr": { "$eq": [ "$_id", "$$programid" ] }}}
        ],
        "as": "programs"
      }},
      { "$lookup": {
        "from": ProgramManagers.collection.name,
        "let": { "marketId": "$marketId" },
        "pipeline": [
          { "$match": { "$expr": { "$eq": [ "$_id", "$$marketId" ] }}},
          { "$lookup": {
            "from": Programs.collection.name,
            "let": { "id": "$id" },
            "pipeline": [
              { "$match": { "$expr": { "$eq": [ "$_id", "$$id" ] }}}
            ],
            "as": "programs"
          }}
        ],
        "as": "programManagers"
      }}
    ],
    "as": "marketManagers"
  }}
])