0

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.

Ale Gu
  • 146
  • 9
  • Possible duplicate of [$lookup multiple levels without $unwind?](https://stackoverflow.com/questions/49953780/lookup-multiple-levels-without-unwind) – Ashh May 16 '19 at 16:56
  • can you clarify what you're asking? whats `Coleg`? is it the users? if not how is it mapped? – Tom Slabbaert May 16 '19 at 17:48
  • Yes, Coleg is the user model....I modified it... – Adrian Dragomir May 17 '19 at 12:21
  • The idea is using the $group I can "aggregate" the users by location since I have the location as a schema property: 2 users Chicago, 4 users Toronto, 6 users Houston. But when I tried to use the $group to "aggregate" users by country I've got: 2 users USA, 4 users Canada, 6 users USA, instead of : 8 users USA, 4 users Canada – Adrian Dragomir May 17 '19 at 12:53

0 Answers0