【问题标题】:Get n number of documents from a collection using MongoDB/MongoEngine使用 MongoDB/MongoEngine 从集合中获取 n 个文档
【发布时间】:2020-10-09 20:48:01
【问题描述】:

大家好,我在这样的集合中有一个文档。 (忽略问题的荒谬)。

[
    {
        "tag": "english",
        "difficulty": "hard",
        "question": "What are alphabets",
        "option_1": "98 billion light years",
        "option_2": "23.3 trillion light years",
        "option_3": "6 minutes",
        "option_4": "It is still unknown",
        "correct_answer": "option_1",
        "id": "5f80befbaaf3c9ce2f4e2fb9"
    }
]

有多个文档,例如这个(10000)。

我正在尝试使用flask-restful 编写一个python get 函数以从该集合中获取n 的文档数。 目前,我对如何编写 MongoEngine 查询感到困惑。

这就是我根据它获取单个文档的方法。

def get(self,id):
        questions = Question.objects.get(id=id).to_json()
        return Response(questions,
                    mimetype="application/json",
                    status = 200)

对于n 的文档数量,我无法弄清楚里面要写什么。

    def get_n_questions(self,n):
        body = request.get_json(force =True)
        questions = ???
        return Response(questions,
                    mimetype="application/json",
                    status = 200)

【问题讨论】:

  • 为什么不用filter 而不是get

标签: python mongodb mongoengine


【解决方案1】:

您可以在查询集上使用 limit(n) 方法 (doc)。这将让您从集合中检索 n 个第一个文档。

在你的情况下,这意味着:

questions = Question.objects().limit(n).to_json()

您可能还对 skip(n) 方法感兴趣,这将允许您进行分页(例如类似于 MySQL 的限制/偏移)。

【讨论】:

    猜你喜欢
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    相关资源
    最近更新 更多