0Pricing
MongoDB Academy · 课时

比较运算符:$eq、$gt、$lt、$in

您将使用比较运算符,根据数值范围、精确匹配和列表成员关系筛选文档。

比较运算符:$eq、$gt、$lt、$in 是 CoddyKit 上的免费 MongoDB Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 MongoDB Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 MongoDB Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Beyond Equality Filters

Simple equality filters like { status: 'active' } are useful, but real queries need more nuance. MongoDB provides a rich set of query operators prefixed with $ that express conditions beyond simple equality. These operators let you filter by numeric ranges, membership in a list, value presence, and pattern matching.

Comparison operators are the most commonly used category. They work on any comparable BSON type: numbers, strings (lexicographic comparison), dates, and even ObjectIds (chronological order, since ObjectIds encode timestamps).

$eq: Explicit Equality

The $eq operator explicitly tests for equality: { age: { $eq: 30 } }. In most cases, the shorthand { age: 30 } is identical and preferred for readability—$eq is mainly useful when the operator is needed inside another expression like $expr.

One difference: $eq inside aggregation pipeline expressions is required when comparing two field values (e.g., { $eq: ['$price', '$salePrice'] }). In regular find filters, stick to the shorthand equality syntax unless a specific context requires the operator form.

// These two queries are equivalent in find()
db.users.find({ age: 30 });
db.users.find({ age: { $eq: 30 } });

// $eq is useful inside $expr for field-to-field comparison:
db.products.find({
  $expr: { $eq: ['$price', '$salePrice'] }
});
// Returns products where price equals salePrice

$gt and $gte: Greater Than

$gt (greater than) and $gte (greater than or equal) filter documents where a field's value exceeds a threshold. These work on numbers, dates, strings (lexicographic order), and ObjectIds.

Date comparisons are particularly powerful: { createdAt: { $gte: new Date('2024-01-01') } } finds all documents created since January 1, 2024. This query can use an index on createdAt for O(log n) performance, making date-range queries extremely efficient even on large collections.

// Numeric range
db.products.find({ price: { $gt: 100 } });
// price > 100

db.employees.find({ salary: { $gte: 50000 } });
// salary >= 50000

// Date comparison
db.orders.find({
  createdAt: { $gte: new Date('2024-01-01') }
});
// Orders placed since Jan 1, 2024

// String comparison (lexicographic)
db.users.find({ lastName: { $gte: 'M' } });
// Last names starting with M-Z

$lt and $lte: Less Than

$lt (less than) and $lte (less than or equal) are the complements of $gt/$gte. Combine both operators on the same field to create a range query—MongoDB applies both conditions to the same field, equivalent to SQL's BETWEEN.

Range queries on indexed fields are very efficient because MongoDB can seek to the lower bound in the index and scan forward to the upper bound, touching only the relevant entries. This is one of the primary reasons to index fields you frequently filter by range.

// Price < 50
db.products.find({ price: { $lt: 50 } });

// Age <= 17 (minors)
db.users.find({ age: { $lte: 17 } });

// Range query: price between 20 and 100 (inclusive)
db.products.find({ price: { $gte: 20, $lte: 100 } });
// Equivalent SQL: WHERE price BETWEEN 20 AND 100

// Date range: orders placed last week
const weekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
db.orders.find({ createdAt: { $gte: weekAgo, $lte: new Date() } });

$ne: Not Equal

$ne (not equal) matches documents where a field's value is not equal to the specified value. It also matches documents where the field does not exist at all—because a missing field is implicitly not equal to any value.

Be cautious with $ne on large, unindexed collections: MongoDB typically cannot use an index to satisfy a negation efficiently and may fall back to a collection scan. For heavily filtered queries, prefer positive conditions ($eq, $in) over negative ones when possible.

// Find orders that are not cancelled
db.orders.find({ status: { $ne: 'cancelled' } });

// Find users who have NOT set a display name
// ($ne also matches missing field)
db.users.find({ displayName: { $ne: null } });

// Caution: $ne on non-indexed field scans full collection
// Index the field if used frequently:
db.orders.createIndex({ status: 1 });
db.orders.find({ status: { $ne: 'cancelled' } }); // Uses index

$in: Match Any Value in a List

$in matches documents where a field's value equals any value in a provided array. It is the MongoDB equivalent of SQL's IN clause. This is far more concise than writing multiple $or conditions for the same field.

On an indexed field, $in is implemented as multiple point lookups in the index tree—one per value in the array—which is very efficient. For large lists (hundreds of values), performance degrades, but for typical use cases (5-20 values), $in is a great choice.

// Find products in specific categories
db.products.find({
  category: { $in: ['Electronics', 'Computers', 'Peripherals'] }
});
// Equivalent SQL: WHERE category IN ('Electronics', 'Computers', 'Peripherals')

// Find orders with specific statuses
db.orders.find({
  status: { $in: ['pending', 'processing', 'shipped'] }
});

// $in on array field: matches if arrays share any element
db.products.find({
  tags: { $in: ['sale', 'clearance'] }
}); // Products with 'sale' OR 'clearance' in their tags array

$nin: Not In a List

$nin (not in) is the negation of $in—it matches documents where the field's value is not in the provided array (and also matches documents where the field is absent). Like $ne, it can be less efficient than $in because it often requires scanning documents.

A practical use case: excluding a known set of IDs. If a user has blocked certain other users, you might exclude their content: { authorId: { $nin: blockedUserIds } }. Keep the exclusion list small for best performance.

// Exclude archived and deleted statuses
db.tickets.find({
  status: { $nin: ['archived', 'deleted', 'spam'] }
});

// Exclude a user's own posts from their feed
const blockedIds = [ObjectId('...'), ObjectId('...')] ;
db.posts.find({
  authorId: { $nin: blockedIds }
}).sort({ createdAt: -1 }).limit(20);

Combining Comparison Operators

You can combine multiple comparison operators on the same field or different fields in a single query. When operators appear on the same field in one object, they act as an implicit AND—both conditions must be true. When they are on different fields, both conditions must also be true.

Build complex filters by thinking about each field independently and combining conditions. MongoDB evaluates all field conditions together, using indexes where available to minimize the documents examined.

// Products priced between $20-$100, in stock, created this year
const thisYear = new Date('2024-01-01');
db.products.find({
  price: { $gte: 20, $lte: 100 },    // Range on price
  stock: { $gt: 0 },                  // In stock
  category: { $in: ['Electronics', 'Home'] },  // Category filter
  createdAt: { $gte: thisYear }       // Created this year
}).sort({ price: 1 });

Comparison Operators on Dates

Date comparisons are among the most common uses of comparison operators in real applications. MongoDB's Date BSON type stores dates as 64-bit milliseconds, so all comparison operators work naturally on date fields.

Common patterns include: finding records created in the last N days, filtering active subscriptions that expire after today, and range queries for reporting periods. Always construct Date objects in the query—never compare dates as strings, as lexicographic string comparison gives incorrect results for most date formats.

// Records created in the last 30 days
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
db.events.find({ createdAt: { $gte: thirtyDaysAgo } });

// Subscriptions that expire in the future (still active)
db.subscriptions.find({ expiresAt: { $gt: new Date() } });

// Orders placed on a specific day (date range for one day)
const startOfDay = new Date('2024-06-01T00:00:00Z');
const endOfDay = new Date('2024-06-01T23:59:59.999Z');
db.orders.find({ createdAt: { $gte: startOfDay, $lte: endOfDay } });

Performance: Indexes and Comparison Queries

Comparison operators benefit enormously from indexes. An index on a numeric field turns an O(n) scan into O(log n + result size). Key points:

  • Range queries ($gt, $lt) can use a single-field index to navigate directly to the range start
  • $in performs multiple point lookups in the index—one per value
  • Negation operators ($ne, $nin) often scan the index rather than using point lookups, so they are less efficient
  • Use explain('executionStats') to verify your comparison queries use IXSCAN and not COLLSCAN
// Verify range query uses index
db.products.find({ price: { $gte: 20, $lte: 100 } })
  .explain('executionStats');
// Look for: winningPlan.stage = 'IXSCAN'
// If COLLSCAN: add index with db.products.createIndex({ price: 1 })

// Create compound index for combined filter:
db.products.createIndex({ category: 1, price: 1 });
// Supports: { category: 'Electronics', price: { $gte: 50 } }

Using Comparison Operators With Aggregation

Comparison operators appear in two contexts: as query operators in find() filters (with the syntax { field: { : value } }) and as expression operators in the aggregation pipeline and stages (with a different syntax: { : ['', value] }).

In , expression operators return a boolean or a computed value. For example, you can add a computed field isExpensive that is true when price exceeds 100: { : { isExpensive: { : ['', 100] } } }. The stage uses the same query syntax as find().

// Comparison in aggregation pipeline:
db.products.aggregate([
  //  uses same syntax as find()
  { : { price: { : 20, : 100 } } },
  //  uses expression operator syntax:
  {
    : {
      isExpensive: { : ['', 80] },      // Returns boolean
      discountedPrice: { : ['', 0.9] }  // Computes value
    }
  }
]);

Quick Check

Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.

Lesson Recap

In this lesson you learned: $gt/$gte/$lt/$lte create range conditions on numbers, dates, and strings, and work with indexes for O(log n) range scans, $in matches any value from a list and is significantly more readable and efficient than multiple $or equality conditions on the same field, and $ne/$nin are negation operators that match anything outside the given value/list but are less index-efficient than their positive counterparts. Next up we explore logical operators—$and, $or, $nor, and $not—to combine conditions across different fields.

常见问题解答

「比较运算符:$eq、$gt、$lt、$in」课时是免费的吗?

是的 — 「比较运算符:$eq、$gt、$lt、$in」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 MongoDB Academy 课程的其余内容,请升级到 CoddyKit PRO。 MongoDB Academy 课程共包含 4 节课。

「比较运算符:$eq、$gt、$lt、$in」这节课中我会学到什么?

您将使用比较运算符,根据数值范围、精确匹配和列表成员关系筛选文档。 你通过在浏览器中直接运行的动手代码来练习 MongoDB Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 MongoDB Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 MongoDB Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「比较运算符:$eq、$gt、$lt、$in」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 MongoDB Academy 课中编写并运行代码吗?

能。每节 MongoDB Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 比较运算符:$eq、$gt、$lt、$in
  2. 逻辑运算符:$and、$or、$nor、$not
  3. 元素运算符与类型检查
  4. 正则查询与模式匹配
← 返回 MongoDB Academy