本文介绍了如何计算 mongo db 中的 $lookup 字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚接触mongodb,现在需要计算一个$lookup字段,可以吗?

我有过这样的经历:

result = await company.aggregate([{$查找:{来自:'用户焦点',本地字段:'_id',外国字段:'值',如:'focusUsers'}},{$项目:{名称: 1,焦点用户:{用户 ID: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}]

有可能吗?怎么做?请高手给点建议,先谢谢了!

解决方案

您可以使用 $size 聚合运算符,用于查找数组的长度.

company.aggregate([{$查找":{"from": "userFocus","localField": "_id","foreignField": "值","as": "focusUsers"}},{$项目":{名称":1,焦点用户":1,"focusCount": { "$size": "$focusUsers" }}}])

I'm quite new in mongodb, now I need to count a $lookup field, is it possible?

I had something like this:

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

and the result looks like this:

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

Now I want an extra column shows the focusUsers count, in other words, I want a result like the following:

[
  {_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}
]

Is it possible? How to do that? Please some experts advice, thanks in advance!

解决方案

You can use $size aggregation operator to find the length of an array.

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

这篇关于如何计算 mongo db 中的 $lookup 字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 09:16