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!
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 ).
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.
$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.
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" }
}}
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With