使用MongoDB / MongoEngine从集合中获取n个文档

时间:2020-10-09 20:48:01

标签: python mongodb mongoengine

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

[
    {
        "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)

1 个答案:

答案 0 :(得分:0)

您可以在查询集上使用a = [] 方法(doc)。这样您就可以从集合中检索n个firsts文档。

对于您而言,这意味着:

a = re.findall(r"nendobj(.*?)W 3\.0",cadena)

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