Home > Mobile >  Mongodb group by a nested field
Mongodb group by a nested field

Time:02-25

db.logs.aggregate([{$match: { _device: { $in: devices }, takenTimestamp: {$gt: 1547650800 } }}, { $lookup: { 
        from: "users", 
        localField: "_deviceTakenByUser", 
        foreignField: "_id", 
        as: "user" 
    }}, { $project: { _id: 0, user: { email: 1 }}}  ])

I know want to get distinct values from the user email, is it possible to do so? Can I do it with grouping?

CodePudding user response:

After your $lookup, user is a list of users.

You can do an $unwind to split it

And then use a $group an the email field to have a list of all the emails

...
{
    "$unwind": "$user"
},
{
    "$group": {
        "_id": "$user.email" 
    }
}
  • Related