文档菜单
文档首页
/ / /
Node.js 驱动程序
/ /

指定查询

在本页

  • 概述
  • 文本值查询
  • 比较运算符
  • 逻辑运算符
  • 元素运算符
  • 评估运算符

大多数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运算符的参考手册条目。

返回

更新插入