Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to count a $lookup fields in mongo db?

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!

like image 531
Jeff Tian Avatar asked Sep 19 '18 10:09

Jeff Tian


People also ask

How do I count fields in MongoDB?

First stage $project is to turn all keys into array to count fields. Second stage $group is to sum the number of keys/fields in the collection, also the number of documents processed. Third stage $project is subtracting the total number of fields with the total number of documents (As you don't want to count for _id ).

How do you count aggregation?

Returns as a BIGINT the number of rows in each group where the expression is not NULL . If the query has no GROUP BY clause, COUNT returns the number of table rows. The COUNT aggregate function differs from the COUNT analytic function, which returns the number over a group of rows within a window.

What is $lookup in MongoDB?

$lookup performs an equality match on the localField to the foreignField from the documents of the from collection. If an input document does not contain the localField , the $lookup treats the field as having a value of null for matching purposes.


1 Answers

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" }
  }}
])
like image 150
Ashh Avatar answered Sep 23 '22 04:09

Ashh