假设我的架构如此:
class User(Document):
username = StringField()
password = StringField()
category = StringField()
想象一下,我们有这些现有的类别:"avengers", "justice-leaguers", "villains"
,我想对"group by"
执行User.objects.all()
查询,以便我可以得到这样的内容:
[
[<User: IronMan object>, <User: Thor object>, <User: Hulk object>],
[<User: Superman object>,<User: Batman object>],
[<User: Ultron object>, <User: Joker object>, <User: LexLuthor object>]
]
或者更好:
{
"avengers": [<User: IronMan object>, <User: Thor object>, <User: Hulk object>],
"justice-leaguers": [<User: Superman object>,<User: Batman object>],
"villains": [<User: Ultron object>, <User: Joker object>, <User: LexLuthor object>]
}
我查看了MongoEngine的文档,但还没有找到任何有用的信息。多谢你们!
答案 0 :(得分:15)
由于OP要求使用mongoengine(这就是我需要的),这里有一个使用mongoengine的例子:
categories = User.objects.aggregate([{
'$group': { '_id': '$category', 'username': { '$push': '$username' }}
}])
这将返回一个pymongo命令游标迭代器。
print list(categories)
将返回:
[{ "_id": "villains", "username": ["Ultron", "Joker", "LexLuthor"]},
{ "_id": "justice-leagers", "username": ["Superman", "Batman"]},
{ "_id": "avengers", "username": ["IronMan", "Thor", "Hulk"]}]
答案 1 :(得分:3)
使用aggregation framework,您只需按类别$group
个文档:
db.User.aggregate([
{
$group: { _id: "$category", username: { $push: "$username" }}
}
])
使用$push聚合函数,您将构建一个包含共享相同类别的所有用户名的数组。
给你样本数据:
> db.User.find({},{category:1,username:1,_id:0})
{ "category" : "avengers", "username" : "IronMan" }
{ "category" : "avengers", "username" : "Thor" }
{ "category" : "avengers", "username" : "Hulk" }
{ "category" : "justice-leagers", "username" : "Superman" }
{ "category" : "justice-leagers", "username" : "Batman" }
{ "category" : "villains", "username" : "Ultron" }
{ "category" : "villains", "username" : "Joker" }
{ "category" : "villains", "username" : "LexLuthor" }
这将产生:
{ "_id" : "villains", "username" : [ "Ultron", "Joker", "LexLuthor" ] }
{ "_id" : "justice-leagers", "username" : [ "Superman", "Batman" ] }
{ "_id" : "avengers", "username" : [ "IronMan", "Thor", "Hulk" ] }