That aggregate query you posted seems about right, only you'd have to pass an object to $addToSet
:
db.rentals.aggregate({ "$group" :
{ _id: "$user_id",
rental_count : {$sum : 1},
rentals : {'$addToSet' :
{ "item_id" : '$item_id',
"rental_id" : "$_id",
"name" : "$name"
}
} } } );
Given your sample data, this results in
{
"result" : [
{
"_id" : 2,
"rental_count" : 2,
"rentals" : [
{
"item_id" : 8,
"rental_id" : "3",
"name" : "Third rental"
},
{
"item_id" : 7,
"rental_id" : "2",
"name" : "Second rental"
}
]
},
{
"_id" : 1,
"rental_count" : 1,
"rentals" : [
{
"item_id" : 6,
"rental_id" : "1",
"name" : "First rental"
}
]
}
],
"ok" : 1
}
This doesn't have the exact naming you desired, but changing that is the easiest part and I don't want to steal all the fun :-)