Hello, @Ezequias_Rocha!
As @steevej already pointed out, it is possible to do with $lookup operator.
Let me show you by an example.
Assume, we have the following dataset:
db.players.insertMany([
{ player: 'Bob', fromTeam: 'A' },
{ player: 'Sam', fromTeam: 'B' },
{ player: 'Steeve', fromTeam: 'B' },
]);
db.teams.insertMany([
{ team: 'A', country: 'US' },
{ team: 'B', country: 'Canada' },
]);
db.coaches.insertMany([
{ coach: 'Daniel', yearOfExperience: 10 },
]);
To count the documents in each collection and get the result like this:
{ "totalPlayers" : 3, "totalTeams" : 2, "totalCoaches" : 1 }
We can use the following aggregation, that uses a set of $lookup stages with nested pipeline:
db.players.aggregate([
// count documents in the current collection
{
$count: 'totalPlayers',
},
// join other collections, in which you need
// to count documents
{
$lookup: {
from: 'teams',
pipeline: [
{
// count the documents in this specific
// collection with the $count stage
$count: 'result',
},
],
as: 'totalTeams',
},
},
{
$lookup: {
from: 'coaches',
pipeline: [
{
$count: 'result',
},
],
as: 'totalCoaches',
},
},
// $convert arrays, returned by $lookup pipelines,
// so we count easily reach the 'result' prop
{
$unwind: '$totalTeams',
},
{
$unwind: '$totalCoaches',
},
// reset the total-props by reaching the 'result' value
{
$addFields: {
totalTeams: '$totalTeams.result',
totalCoaches: '$totalCoaches.result',
},
},
]).pretty();