使用 Flask 遍历数组以输入 PyMongo 搜索

Using Flask to iterate over an array to input into a PyMongo search

我有一个数组,比方说这个:

[ObjectId('5feceb11b5ffb79d03df04a0'), ObjectId('600c1c83e5c06febfb7f8ab5'), ObjectId('5fe8f9227221766fa23707d0'), ObjectId('5fe995f93137252b3bb37bbe')]

据此,我想在数据库中找到每个 ObjectId 的配置文件。

所以我需要做的就是这样:

person = mongo.db.users.find_one({"username": **each ObjectId**})

其中每个 ObjectId 都是数组中的 ObjectId 之一。

然后这样:

person == user1; and
person == user9; and
person == user13; and
person == user16

从那里,我可能可以在 Jinja 中将其作为 for 循环来管理。

如果您希望返回多份文件,您 也可以使用 find() 方法,但根据您的用例,您可能需要使用 $in 运算符,如果您的列表很大,它可能会减慢速度,但如果批量执行保存往返行程到db 并获得更好的性能。

然后确保列表中的每个元素都具有 bson ObjectId 类型而不是 python str,如果没有,您可以键入 cast python str 通过导入到 bson ObjectId ObjectId

>>> from bson import ObjectId
>>> print(type(ObjectId('5e9dc0548a4617a55665624f')))
>>> <class 'bson.objectid.ObjectId'>

所以在确保你有一个 ObjectId 的列表之后,你可以使用 find$in 进行查询,如下所示:

>>> users = [ObjectId('5e9dc0548a4617a55665624f'),ObjectId('5e9dc0a75db97122a193aa51')]
>>> q = collection.find({'username': { "$in": users}})