指定查询
Overview
大多数 CRUD 操作都允许通过在查询文档中指定匹配条件来缩小匹配文档的范围。查询文档包含一个或多个应用于特定字段的查询运算符,这些特定字段确定要包含在结果集中的文档。
在查询文档中,您可以将字段与文字值(例如 { title: 'The Room' }
)进行匹配,也可以组合应用 查询操作符来表达更复杂的匹配条件。本指南介绍了 MongoDB 以下类别的查询操作符,并举例说明如何使用:
要按照本指南中的示例进行操作,请使用以下代码片段将描述水果的文档插入 myDB.fruits
集合中:
const myDB = client.db("myDB"); const myColl = myDB.collection("fruits"); await myColl.insertMany([ { "_id": 1, "name": "apples", "qty": 5, "rating": 3 }, { "_id": 2, "name": "bananas", "qty": 7, "rating": 1, "color": "yellow" }, { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 }, { "_id": 4, "name": "avocados", "qty": 3, "rating": 5 }, ]);
注意
您的查询操作可能会返回对包含匹配文档的游标的引用。 要学习;了解如何检查存储在游标中的数据,请参阅游标基础知识页面。
字面值查询
字面值查询根据您查询文档中提供的值来进行查询,且返回的结果将精准匹配您提供的值。一个字面值查询由两部分组成:一个字段名和一个值。此类查询返回的文档必须包含一个与所提供名称完全相同的字段,且该字段的值也必须与提供的值完全相同。以下操作使用了字面查询来搜索文档,目标文档需包含一个名为“name”的字段,且该字段的值为“apples”:
const query = { "name": "apples" }; const cursor = myColl.find(query); for await (const doc of cursor) { console.dir(doc); }
此代码片段返回以下结果:
{ "_id": 1, "name": "apples", "qty": 5, "rating": 3 }
注意
字面值查询相当于 $eq
比较操作符。因此,以下两个查询是等效的:
myColl.find({ rating: { $eq: 5 } });
myColl.find({ rating: 5 });
比较操作符。
比较操作符允许您根据与集合中值的比较结果来查询数据。常见的比较操作符包括用于“大于”比较的 $gt
、用于“小于”比较的 $lt
以及用于“不等于”比较的 $ne
。以下操作使用比较操作符 $gt
搜索 qty
字段值大于 5
的文档并将其打印出来:
// $gt means "greater than" const query = { qty: { $gt : 5 } }; const cursor = myColl.find(query); for await (const doc of cursor) { console.dir(doc); }
此代码片段返回以下结果:
{ "_id": 2, "name": "bananas", "qty": 7, "rating": 1 } { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 }
逻辑操作符
借助逻辑操作符,可以使用应用于字段级操作符结果的逻辑来查询数据。例如,可以使用 $or
方法来查询与 $gt
比较操作符或字面值查询匹配的文档。以下操作使用逻辑操作符 $not
搜索并打印量值不大于 5 的文档:
const query = { qty: { $not: { $gt: 5 }}}; const cursor = myColl.find(query); for await (const doc of cursor) { console.dir(doc); }
此代码片段返回以下结果:
{ "_id": 4, "name": "avocados", "qty": 3, "rating": 5 } { "_id": 1, "name": "apples", "qty": 5, "rating": 3 }
注意
每当查询文档包含多个元素时,将这些元素与隐式 $and
逻辑操作符组合在一起,以确定哪些文档与查询相匹配。因此,以下两个查询是等效的:
myColl.find({ rating: { $eq: 5 }, qty: { $gt: 4 } });
myColl.find({ $and: [ { rating: { $eq: 5 }}, { qty: { $gt: 4 }} ] });
有关比较操作符的更多信息,请参阅参考手册中的比较查询操作符条目。
元素操作符
元素运算符允许您根据字段的存在、缺失或类型进行查询。以下操作使用元素运算符 $exists
搜索包含 color
字段的文档:
const query = { color: { $exists: true } }; const cursor = myColl.find(query); for await (const doc of cursor) { console.dir(doc); }
此代码片段返回以下结果:
{ "_id": 2, "name": "bananas", "qty": 7, "rating": 1, "color": "yellow" }
有关此操作符的更多信息,请参阅 $exists 操作符的参考手册条目。
评估操作符
求值操作符允许您在查询集合中的文档时执行更高级别的逻辑,例如正则表达式和文本搜索。常见的求值操作符包括 $regex
和 $text
。以下操作使用求值操作符 $mod
来搜索qty
字段值可被 3 整除(余数为 0)的文档:
// $mod means "modulo" and returns the remainder after division const query = { qty: { $mod: [ 3, 0 ] } }; const cursor = myColl.find(query); for await (const doc of cursor) { console.dir(doc); }
此代码片段返回以下结果:
{ "_id": 3, "name": "oranges", "qty": 6, "rating": 2 } { "_id": 4, "name": "avocados", "qty": 3, "rating": 5 }
有关此操作符的更多信息,请参阅参考手册中的 $mod 操作符条目。