I have two collections.
collection1:
[
{
"_id": "user1"
},
{
"_id": "user2"
}
]
collection2:
[
{
"name": "test",
"Info": {
"initiatedBy": "user1"
}
},
{
"name": "Test LFE",
"Info": {
"initiatedBy": "user1"
}
},
{
"name": "Test uuE",
"Info": {
"initiatedBy": "user2"
}
}
]
I want the final result as
user1: 2
. Because user1 created 2 records.
user2: 1
. Because only one record was created by user2.
I used the below query to execute in Mongo Compass but was not given the exact result.
db.collection1.aggregate([
{
$lookup: {
from: "collection2",
localField: "_id",
foreignField: "Info.initiatedBy",
as: "matchedRecords"
}
},
{
$unwind: "$matchedRecords"
},
{
$group: {
_id: null,
count: {
$sum: "$matchedRecords.fieldToCount"
}
}
}
])
Please provide your suggestions to correct the above query.
I don't see that any reason to $unwind
the matchedRecords
array and perform $group
.
Instead, you can get the size of matchedRecords
array with $size
operator.
db.collection1.aggregate([
{
$lookup: {
from: "collection2",
localField: "_id",
foreignField: "Info.initiatedBy",
as: "matchedRecords"
}
},
{
$project: {
_id: 1,
count: {
$size: "$matchedRecords"
}
}
}
])