如何在 mongoengine 中做 "group by"

How to do "group by" in mongoengine

假设我的架构如下所示:

class User(Document):
  username = StringField()
  password = StringField()
  category = StringField()

假设我们有这些现有类别:"avengers", "justice-leaguers", "villains",我想对 User.objects.all() 执行 "group by" 查询,这样我就可以得到这样的结果:

[
 [<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 的文档,但尚未找到任何有用的信息。谢谢你们!

使用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" ] }

由于 OP 要求使用 mongoengine(这就是我所需要的),这里是使用 mongoengine 的示例:

categories = User.objects.aggregate([{
    '$group': { '_id': '$category', 'username': { '$push': '$username' }}
}])

这将 return 一个 pymongo 命令游标迭代器。

print list(categories)

会 return:

[{ "_id": "villains", "username": ["Ultron", "Joker", "LexLuthor"]},
 { "_id": "justice-leagers", "username": ["Superman", "Batman"]},
 { "_id": "avengers", "username": ["IronMan", "Thor", "Hulk"]}]