1

aggregate与 mongoengine 一起使用时,它返回一个 CommandCursor 而不是 mongoengine 对象列表,这意味着 mongonengine 并没有真正被使用,

例如:如果某些文档没有标题字段,则会引发错误。如何将结果转换为 mongoengine 对象?

class Post(Document):
    title = StringField(max_length=120, required=True)
    author = ReferenceField(User)

Host.objects()
# [<Post: Post object>, <Post: Post object>, ...]

pipeline = [
    {
        "$match": {
            'types': type,
        }
    },
    {
        "$project": {
            "name": 1,
            'brating': {
                "$divide": [
                    {"$add": ["$total_score", 60]},
                    {"$add": ["$total_votes", 20]}
                ]
            }
        }
    },
    {"$sort": {"brating": -1}},
    {"$limit": 100}

]

Host.objects.aggregate(*pipeline)
# <class 'pymongo.command_cursor.CommandCursor'>

list(Host.objects.aggregate(*pipeline))
# <class 'list'>
4

1 回答 1

1

aggregate函数只是底层pymongo 函数的快捷方式。

返回的文档aggregate可能涉及某些$group或其他阶段,这意味着它们与您的对象模型无关,因此 mongoengine 无法将它们转换为 mongoengine 对象。

对于您的管道,您正在使用一个阶段来返回一种只有和字段$project的新型文档。namebrating

Mongoengine 不能在这里做你想做的事,所以你有几个选择:

  • brating字段存储在Post文档上。创建帖子时将评分初始化为 0,当更新$total_score$total_votes更新时,也会更新评分。

  • 接受您正在取回非 mongoengine 对象并相应地处理它们。光标将产生普通的 python 字典,然后您可以访问这些字段post['name']post['brating']在您的客户端代码中。

  • .objects在客户端使用普通查询和排序。

如果您有很多文档,但对于少数文档,请尝试以下步骤,最后一步将不经意间成为问题:

posts = Post.objects(types=type).only("name", "total_score", "total_votes")
top_posts = sorted(list(posts),key=lambda p: (p.total_score+60)/(p.total_votes+20))[:100]
于 2016-12-29T16:14:22.653 回答