如何计算mongo db中的$ lookup字段?

时间:2018-09-19 10:59:28

标签: mongodb aggregation-framework

我在mongodb中很陌生,现在我需要计算一个$ lookup字段,有可能吗?

我有这样的东西:

result = await company.aggregate([
  {
    $lookup: {
      from: 'userFocus',
      localField: '_id',
      foreignField: 'value',
      as: 'focusUsers'
    }
  },
  {
    $project:{
      name: 1,
      focusUsers: {userId: 1}
    }
  }
])

结果看起来像这样:

[
  {_id: 'xxxx', name: 'first company', focusUsers: [user1, user2, user3...]},
  {_id: 'yyyy', name: 'second company', focusUsers: []},
  {_id: 'zzzz', name: 'third company', focusUsers: []}
]

现在,我想要一个额外的列来显示focusUsers的数量,换句话说,我想要一个类似以下的结果:

[
  {_id: 'xxxx', name: 'first company', focusUsers: [user1, user2, user3], focusCount: 3},
  {_id: 'yyyy', name: 'second company', focusUsers: [], focusCount: 0},
  {_id: 'zzzz', name: 'third company', focusUsers: [], focusCount: 0}
]

有可能吗?怎么做?请一些专家建议,在此先感谢!

1 个答案:

答案 0 :(得分:3)

您可以使用$size聚合运算符来查找数组的长度。

company.aggregate([
  { "$lookup": {
    "from": "userFocus",
    "localField": "_id",
    "foreignField": "value",
    "as": "focusUsers"
  }},
  { "$project": {
    "name": 1,
    "focusUsers": 1,
    "focusCount": { "$size": "$focusUsers" }
  }}
])