与引用集合的Mongodb聚合

时间:2017-11-27 09:01:55

标签: mongodb aggregation-framework

我想获得我的二级联盟用户列表,我设计了像

这样的集合

用户

{ 
    "_id" : ObjectId("5a1b9df7bfdbfef2d4f1e9f3"), 
    "name" : "name 1",
    "affKey" : "H1g-CfFxG", 
}
{ 
    "_id" : ObjectId("5a1bce5e9a2918f71a9ac4fb"), 
    "name" : "name 2",
    "affKey" : "K1gKJfFxG", 
}

affilites

{  
    "affKey" : "H1g-CfFxG", 
    "affUsers" : [ 
        ObjectId("5a1bce5e9a2918f71a9ac4fb")
    ], 
}

{  
    "affKey" : "K1gKJfFxG", 
    "affUsers" : [
        ObjectId("5a1b9e43bfdbfef2d4f1e9f8"),
        ObjectId("5a1b9e43bfdbfef2d4f1e911"),
    ], 
}

此处我在affiliate.affKey中保存的新内容基于Users.affKey

现在我想获得我的第一级和第二级关联公司的列表,即5a1b9e43bfdbfef2d4f1e9f65a1bce5e9a2918f71a9ac4fb以及第一级关联公司的关联公司列表。

期待结果如

{
  first: [first level affiliates] // 1 result 
  second: [second level affiliates] // 2 results
}

1 个答案:

答案 0 :(得分:1)

对于这种情况,您必须采取一些步骤才能获得预期的结果。可以遵循以下步骤

  
      
  1. $lookup affiliets
  2. affKey个集合   
  3. 然后您必须$lookup users集合才能获得参考用户信息
  4.   
  5. 之后,您必须$lookup再次获得第二级用户的affiliets集合affKey
  6.   

所以查询可以像下面那样

db.users.aggregate([
  {
    $lookup: {
      from: "affilites",
      localField: "affKey",
      foreignField: "affKey",
      as: "affUsers"
    }
  },
  {
    $project: {
      name: 1,
      affKey: 1,
      first: {$arrayElemAt: ["$affUsers.affUsers", 0]},
      secondLevelUserId: {$arrayElemAt: ["$affUsers.affUsers", 0]}
    }
  },
  { $unwind: { path: "$secondLevelUserId", "preserveNullAndEmptyArrays": true }},
  {
    $lookup: {
      from: "users",
      localField: "secondLevelUserId",
      foreignField: "_id",
      as: "secondLevelUser"
    }
  },
  {
    $project: {
      name: 1,
      affKey: 1,
      first: 1,
      secondLevelUser: {$arrayElemAt: ["$secondLevelUser", 0]}
    }
  },
  {
    $lookup: {
      from: "affilites",
      localField: "secondLevelUser.affKey",
      foreignField: "affKey",
      as: "secondLevelUser"
    }
  },
  {
    $project: {
      name: 1,
      affKey: 1,
      first: 1,
      second: {$arrayElemAt: ["$secondLevelUser.affUsers", 0]}
    }
  },
  {
    $unwind: {
      "path": "$second",
      "preserveNullAndEmptyArrays": true
    }
  },
  {
    $group: {
      _id: "$_id",
      name: {$first: "$name"},
      affKey: {$first: "$affKey"},
      first: {$first: "$first"},
      second: {$addToSet: "$second"}
    }
  }
]);

执行查询后,您将获得类似于下面的结果

第一份文件:

{
    "_id" : ObjectId("5a1b9df7bfdbfef2d4f1e9f3"),
    "name" : "name 1",
    "affKey" : "H1g-CfFxG",
    "first" : [ 
        ObjectId("5a1bce5e9a2918f71a9ac4fb")
    ],
    "second" : [ 
        ObjectId("5a1b9e43bfdbfef2d4f1e911"), 
        ObjectId("5a1b9e43bfdbfef2d4f1e9f8")
    ]
}

第二份文件

{
    "_id" : ObjectId("5a1bce5e9a2918f71a9ac4fb"),
    "name" : "name 2",
    "affKey" : "K1gKJfFxG",
    "first" : [ 
        ObjectId("5a1b9e43bfdbfef2d4f1e9f8"), 
        ObjectId("5a1b9e43bfdbfef2d4f1e911")
    ],
    "second" : []
}