MongoDB 查询使用操作符(以 $ 为前缀)来表达超越简单相等比较的条件 — 比较、逻辑、元素和数组操作符。它们是用于筛选文档的过滤器文档的基础。
比较操作符
js
db..({ : { : } });
db..({ : { : , : } });
db..({ : { : } });
db..({ : { : [, ] } });
db..({ : { : [] } });
MongoDB 查询使用操作符(以 $ 为前缀)来表达超越简单相等比较的条件 — 比较、逻辑、元素和数组操作符。它们是用于筛选文档的过滤器文档的基础。
db..({ : { : } });
db..({ : { : , : } });
db..({ : { : } });
db..({ : { : [, ] } });
db..({ : { : [] } });
$eq $ne → equal / not equal
$gt $gte → greater than / greater-or-equal
$lt $lte → less than / less-or-equal
$in $nin → in / not in a list of values
// $and / $or / $not / $nor combine conditions
db.users.find({ $or: [{ age: { $lt: 18 } }, { age: { $gt: 65 } }] }); // young OR old
db.users.find({ $and: [{ active: true }, { premium: true }] });
// (multiple fields in one filter are AND by default)
db.users.find({ active: true, age: { $gt: 18 } }); // active AND age > 18
过滤器中的多个字段隐含地使用 AND 连接;$or/$and/$not 用于表达更复杂的逻辑。
db.users.find({ email: { $exists: true } }); // field exists
db.users.find({ age: { $type: "number" } }); // field is of a type
// array operators
db.posts.find({ tags: "mongodb" }); // array CONTAINS "mongodb"
db.posts.find({ tags: { $all: ["a", "b"] } }); // contains ALL of these
db.posts.find({ tags: { $size: 3 } }); // array has exactly 3 elements
db.posts.find({ "scores": { $elemMatch: { $gt: 80, $lt: 90 } } }); // an element matching
数组操作符查询数组内部 — $all(包含全部)、$size(长度)、$elemMatch(匹配多个条件的元素),直接匹配值则检查包含关系。
db.users.find({ "address.city": "NY" }); // query a NESTED field with dot notation
查询操作符对于在 MongoDB 中有效地筛选数据至关重要 — 基于条件查找特定文档是任何应用程序的常见需求,所以理解它们是基础的日常知识。
掌握比较操作符($gt、$lt、$in 等用于范围和值匹配)、逻辑操作符($or、$and 以及多个过滤字段隐含 AND)、元素操作符($exists、$type),尤其是数组操作符($all、$size、$elemMatch 以及直接包含匹配)涵盖了你需要的查询条件范围。
数组操作符在 MongoDB 中尤其重要,因为文档通常包含数组(这是文档模型的关键部分),在数组内部查询(包含关系、全元素匹配、元素匹配)是一个常见需求,这也是 MongoDB 查询的独特之处。
理解用于查询嵌套字段的点号表示法(如 "address.city")也是必要的,这是基于 MongoDB 的嵌套文档结构。
由于数据筛选是最常见的数据库操作之一,而 MongoDB 的查询操作符(比较、逻辑、元素,尤其是数组操作符,加上嵌套字段查询)是表达条件以找到正确文档的方式,所以理解查询操作符是必要的、经常使用的 MongoDB 知识 — 相当于掌握 SQL 的 WHERE 条件,对于针对 MongoDB 的文档和数组丰富的数据编写有效查询是必需的,是任何 MongoDB 开发的核心技能。