I'm trying to get the last documents per user in my collection, but I'm not able to retrieve that successfully. I already looked in other posts, but couldn't find (mongo group query how to keep fields and MongoDB : Aggregation framework : Get last dated document per grouping ID , for example)
My problem is that I'm not able to return fields as objects apparently (I'm new to mongo so I hope there is a way).
All I can return are fields like {title, body, username, avatar} and not {title, body, user { username, avatar } }
My collection:
[{
title: 'title 1',
body: 'body 2',
user: {
username: 'a',
avatar: 'avatar 1'
}
},
{
title: 'title 2',
body: 'body 2',
user: {
username: 'b',
avatar: 'avatar 2'
}
},
{
title: 'title 3',
body: 'body 3',
user: {
username: 'b',
avatar: 'avatar 2'
}
}]
I want to return after group by:
[{
title: 'title 1',
body: 'body 2',
user: {
username: 'a',
avatar: 'avatar 1'
}
},
{
title: 'title 3',
body: 'body 3',
user: {
username: 'b',
avatar: 'avatar 2'
}
}]
Example of one of the queries I tried:
// this only returns the avatar and not the username...
db.collection.aggregate([
{ '$sort': { title: 1 } },
{ '$group': {
_id: '$user.username',
body: { $last: '$body' },
title: { $last: '$title' },
user: { $last: '$user.username', $last: '$user.avatar' }
}}])
// this throws an error saying the field 'user ' must be an accumulator object
db.collection.aggregate([
{ '$sort': { title: 1 } },
{ '$group': {
_id: '$user.username',
body: { $last: '$body' },
user: [ { $last: '$user.username', $last: '$user.avatar' } ]
}}
])
With that said, I also want to point out that maybe group is not the way to go. Maybe mongo has a distinct
function that I could use?