I have two MongoDB collections which are joined like that
var userSchema = new Schema({
username: String,
location: {type: mongoose.Schema.Types.ObjectId, ref: 'Location' },
});
var locationSchema = new Schema({
name: {type:String,required: true },
country: String,
});
I need to get 2 reports, one users by location and another users by country.
For the first report I did the following:
User.aggregate(
[
{
$group: {
_id:"$location",
count: {$sum: 1}
}
},
{
$lookup: {
from: 'locations',
localField: '_id',
foreignField: '_id',
as: 'locations',
}
},
{ "$unwind": "$locations" },
{
$sort: {
location: -1,
},
}
],
function (err, result) {
if (err) {
next(err);
} else {
res.json(result);
console.log('result',result);
}
}
)
I do not know how to aggregate the documents from the joined collection to get the second report.