我的表结构如下:
租金:
{
'_id' : '1',
'user_id' : 1,
'item_id' : 6,
'name' : "First rental",
}
{
'_id' : '2',
'user_id' : 2,
'item_id' : 7,
'name' : "Second rental",
}
{
'_id' : '3',
'user_id' : 2,
'item_id' : 8,
'name' : "Third rental",
}
我想要一份按用户分类的租金清单,如下:
{
'user' : '1',
'rental_count': 1,
'rentals' : [
{
'_id' : '1',
'item_id' : 6,
'name' : "First rental"
}
]
'user' : '2',
'rental_count: 2',
'rentals' : [
{
'_id' : '2',
'item_id' : 7,
'name' : "Second rental"
},
{
'_id' : '3',
'item_id' : 8,
'name' : "Third rental"
},
]
}
如何使用mongodb (如果必要的话,我可以使用聚合框架)。
我试过这样的方法:
self.collection.aggregate([
{'$group' => {_id: {user_id: '$user_id'},
rental_items: {'$addToSet' => '$item_id'}
rental_ids: {'$addToSet' => '$_id'}
}
]},
但是它永远不会起作用,因为我在很多不同的集合中都有租金信息,而且我希望每个用户的所有租金都在一个数组中。
发布于 2013-10-16 16:13:56
您发布的聚合查询似乎是正确的,只是您必须将一个对象传递给$addToSet
db.rentals.aggregate({ "$group" :
{ _id: "$user_id",
rental_count : {$sum : 1},
rentals : {'$addToSet' :
{ "item_id" : '$item_id',
"rental_id" : "$_id",
"name" : "$name"
}
} } } );
给定您的示例数据,这将导致
{
"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
}
这没有您想要的确切名称,但更改它是最简单的部分,我不想窃取所有的乐趣:-)
https://stackoverflow.com/questions/19406612
复制相似问题