Docs 菜单

指定查询

在本指南中,您可以了解如何使用 PyMongo 指定查询。

您可以通过创建查询筛选器来优化查询返回的文档集。 查询筛选器是一个表达式,用于指定Atlas Search MongoDB在读取或写入操作中用于匹配文档的 条件。在查询筛选器中,您可以提示驱动程序Atlas Search与您的查询完全匹配的文档,或者您可以组合查询筛选器以Express更复杂的匹配条件。

本指南中的示例对名为fruits的集合运行操作,该集合包含以下文档:

{ "_id": 1, "name": "apples", "qty": 5, "rating": 3, "color": "red", "type": ["fuji", "honeycrisp"] },
{ "_id": 2, "name": "bananas", "qty": 7, "rating": 4, "color": "yellow", "type": ["cavendish"] },
{ "_id": 3, "name": "oranges", "qty": 6, "rating": 2, "type": ["naval", "mandarin"] },
{ "_id": 4, "name": "pineapple", "qty": 3, "rating": 5, "color": "yellow" },

以下代码示例展示了如何创建数据库和集合,然后将样本文档插入集合:

from pymongo import MongoClient
uri = "<connection string URI>"
client = MongoClient(uri)
try:
database = client["sample_fruit"]
collection = database["fruits"]
collection.insert_many([
{ "_id": 1, "name": "apples", "qty": 5, "rating": 3, "color": "red", "type": ["fuji", "honeycrisp"] },
{ "_id": 2, "name": "bananas", "qty": 7, "rating": 4, "color": "yellow", "type": ["cavendish"] },
{ "_id": 3, "name": "oranges", "qty": 6, "rating": 2, "type": ["naval", "mandarin"] },
{ "_id": 4, "name": "pineapple", "qty": 3, "rating": 5, "color": "yellow" },
])
client.close()
except Exception as e:
raise Exception("Error inserting documents: ", e)

字面值查询返回与查询筛选器精确匹配的文档。

以下示例将查询筛选器指定为find()方法的参数。 此代码将返回color字段值为"yellow"的所有文档:

results = collection.find({ "color": "yellow" })
{'_id': 2, 'name': 'bananas', 'qty': 7, 'rating': 4, 'color': 'yellow', 'type': ['cavendish']}
{'_id': 4, 'name': 'pineapple', 'qty': 3, 'rating': 5, 'color': 'yellow'}

提示

查找所有文档

要查找集合中的所有文档,请调用find()方法并向其传递一个空的查询筛选器。 以下示例查找集合中的所有文档:

results = collection.find({})

比较运算符会根据查询筛选器中的指定值评估文档字段值。 以下是常见比较操作符的列表:

  • $gt :大于

  • $lte :小于或等于

  • $ne :不等于

要查看比较操作符的完整列表,请参阅 MongoDB Server 手册中的比较查询操作符指南。

以下示例将查询筛选器中的比较运算符指定为find()方法的参数。 此代码会返回rating字段值大于2的所有文档:

results = collection.find({ "rating": { "$gt" : 2 }})
for f in results:
print(f)
{'_id': 1, 'name': 'apples', 'qty': 5, 'rating': 3, 'color': 'red', 'type': ['fuji', 'honeycrisp']}
{'_id': 2, 'name': 'bananas', 'qty': 7, 'rating': 4, 'color': 'yellow', 'type': ['cavendish']}
{'_id': 4, 'name': 'pineapple', 'qty': 3, 'rating': 5, 'color': 'yellow'}

逻辑操作符通过使用应用于两组或多组表达式结果的逻辑来匹配文档。 以下是逻辑操作符列表:

  • $and ,返回符合所有子句条件的所有文档

  • $or ,返回符合一个子句条件的所有文档

  • $nor ,返回所有符合任何子句条件的文档

  • $not ,返回与表达式匹配的所有文档

要了解有关逻辑操作符的更多信息,请参阅 MongoDB Server 手册中的逻辑查询操作符指南。

以下示例将查询筛选器中的逻辑操作符指定为find()方法的参数。 此代码将返回qty字段值大于5color字段值为"yellow"的所有文档:

results = collection.find({
"$or": [
{ "qty": { "$gt": 5 }},
{ "color": "yellow" }
]
})
for f in results:
print(f)
{'_id': 2, 'name': 'bananas', 'qty': 7, 'rating': 4, 'color': 'yellow', 'type': ['cavendish']}
{'_id': 3, 'name': 'oranges', 'qty': 6, 'rating': 2, 'type': ['naval', 'mandarin']}
{'_id': 4, 'name': 'pineapple', 'qty': 3, 'rating': 5, 'color': 'yellow'}

数组操作符根据数组字段中元素的值或数量来匹配文档。 以下是可用数组操作符的列表:

  • $all ,返回带有数组的文档,而该数组包含查询中的所有元素

  • $elemMatch ,如果大量字段中的元素与查询中的所有条件匹配,则返回文档

  • $size ,返回包含指定大小数组的所有文档

要了解有关数组操作符的更多信息,请参阅 MongoDB Server 手册中的数组查询操作符指南。

以下示例将查询筛选器中的数组运算符指定为find()方法的参数。 此代码返回所有具有包含2元素的type数组字段的文档:

results = collection.find({
"type" : { "$size": 2 }
})
for f in results:
print(f)
{'_id': 1, 'name': 'apples', 'qty': 5, 'rating': 3, 'color': 'red', 'type': ['fuji', 'honeycrisp']}
{'_id': 3, 'name': 'oranges', 'qty': 6, 'rating': 2, 'type': ['naval', 'mandarin']}

元素操作符根据字段的存在或类型查询数据。

要了解有关元素操作符的更多信息,请参阅 MongoDB Server 手册中的元素查询操作符指南。

以下示例将查询筛选器中的元素操作符指定为find()方法的参数。 此代码将返回所有具有color字段的文档:

results = collection.find( { "color" : { "$exists": "true" }} )
for f in results:
print(f)
{'_id': 1, 'name': 'apples', 'qty': 5, 'rating': 3, 'color': 'red', 'type': ['fuji', 'honeycrisp']}
{'_id': 2, 'name': 'bananas', 'qty': 7, 'rating': 4, 'color': 'yellow', 'type': ['cavendish']}
{'_id': 4, 'name': 'pineapple', 'qty': 3, 'rating': 5, 'color': 'yellow'}

求值操作符根据对单个字段或整个文集文件的求值结果返回数据。

以下是常见评估操作符的列表:

  • $text ,对文档执行文本搜索

  • $regex ,返回与指定正则表达式匹配的文档

  • $mod ,对字段的值执行模运算并返回余数为指定值的文档

要查看评估操作符的完整列表,请参阅 MongoDB Server 手册中的评估查询操作符指南。

以下示例将查询筛选器中的评估运算符指定为find()方法的参数。 此代码使用正则表达式返回name字段值至少有两个连续"p"字符的所有文档:

results = collection.find({ "name" : { "$regex" : "p{2,}" }} )
for f in results:
print(f)
{'_id': 1, 'name': 'apples', 'qty': 5, 'rating': 3, 'color': 'red', 'type': ['fuji', 'honeycrisp']}
{'_id': 4, 'name': 'pineapple', 'qty': 3, 'rating': 5, 'color': 'yellow'}

在 Web 应用程序中,对 URL 中文档的 ObjectId 进行编码很常见,如以下代码示例所示:

"/posts/50b3bda58a02fb9a84d8991e"

Web 框架将 的ObjectId 部分作为URL string传递给请求处理程序。您必须先将该string转换为 ObjectId 实例,然后再将其传递给 find_one() 方法。

以下代码示例展示了如何在 Flask 中执行此转换 应用程序。其他 Web 框架的过程类似。

from pymongo import MongoClient
from bson.objectid import ObjectId
from flask import Flask, render_template
client = MongoClient()
app = Flask(__name__)
@app.route("/posts/<_id>")
def show_post(_id):
# NOTE!: converting _id from string to ObjectId before passing to find_one
post = client.db.posts.find_one({'_id': ObjectId(_id)})
return render_template('post.html', post=post)
if __name__ == "__main__":
app.run()

要了解有关查询文档的更多信息,请参阅 MongoDB Server 手册中的查询文档指南。

要学习;了解有关使用PyMongo检索文档的更多信息,请参阅检索数据。

要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: