Query Filters and Common Operators

Use comparison and logical operators, projection, sorting, pagination, and document counts to retrieve exactly the data you need.

🎯 Introduction

Previously, we added four users (Zhang San, 25, Beijing; Li Si, 30, Shanghai; Wang Wu, 22, Guangzhou; and Zhao Liu, 28, Shenzhen) to the user collection in blog_demo. Calling find() without a filter retrieves everything, but applications almost always need to filter their queries.

In this article, you will use comparison operators and logical operators to build filters, use projection to select fields, control results with sorting and pagination, and count documents. These are core MongoDB query skills that we will use throughout the course.


🧱 Comparison Operators: Greater Than, Less Than, and Not Equal

Connect to mongosh using the container and credentials from article 01:

docker exec -it mongo-demo mongosh -u root -p 123456 --authenticationDatabase admin

Then switch to blog_demo:

use blog_demo;

MySQL places conditions after WHERE. MongoDB puts them in the first argument to find(), expressed as a JavaScript object. For an equality match, include the field and value directly:

db.user.find({ city: 'Beijing' });

How do you express “older than 25”? Strings and numbers can be values, but “greater than” requires an operator. MongoDB operators begin with $. Replace the field value with an object whose key is the operator:

// Find users older than 25
db.user.find({ age: { $gt: 25 } });

Think of age: 25 as asking a shop assistant for shelf 25, and age: { $gt: 25 } as handing them a note asking for all shelves after 25. The outer object identifies the field; the inner object specifies the matching rule.

Here are some common comparison operators:

OperatorMeaning
$gtGreater than (>)
$gteGreater than or equal (>=)
$ltLess than (<)
$lteLess than or equal (<=)
$neNot equal (!=)
$inMatches a value in the specified array

You can combine operators on the same field, for example to match ages from 22 through 28:

db.user.find({ age: { $gte: 22, $lte: 28 } });

$in matches any value in an array. For example, find users in Beijing or Shanghai:

db.user.find({ city: { $in: ['Beijing', 'Shanghai'] } });

Use $ne for the opposite condition, such as users outside Beijing:

db.user.find({ city: { $ne: 'Beijing' } });

✨ Logical Operators: $and and $or

An inner object combines conditions on one field. Logical operators combine conditions with AND or OR, including conditions on different fields.

$and requires every condition to match. It accepts an array of conditions, such as users older than 25 who live in Shenzhen:

db.user.find({
    $and: [{ age: { $gt: 25 } }, { city: 'Shenzhen' }],
});
You can usually omit $and: multiple fields in the same filter object are implicitly combined with AND. { age: { $gt: 25 }, city: 'Shenzhen' } is equivalent to the query above and is generally more concise. Explicit $and is mainly useful when you need separate conditions on the same field.

$or requires at least one condition to match. For example, find users younger than 23 or living in Shanghai:

db.user.find({
    $or: [{ age: { $lt: 23 } }, { city: 'Shanghai' }],
});

The distinction is that $in matches several values for one field, while $or matches any of several conditions, potentially across different fields. Use $in for Beijing or Shanghai; use $or when conditions involve different fields.


💡 Projection: Returning Only the Fields You Need

By default, find() returns all fields. An API often needs only two or three; returning everything wastes bandwidth and may expose sensitive information such as passwords.

The second argument to find() controls which fields are returned. This is called projection:

// Return only username and age
db.user.find({ age: { $gt: 25 } }, { username: 1, age: 1 });

In a projection, 1 includes a field. You will also see _id in the result: this automatically generated primary key is included by default. Exclude it explicitly with _id: 0:

db.user.find({ age: { $gt: 25 } }, { username: 1, age: 1, _id: 0 });
Except for _id, you cannot mix 1 (include) and 0 (exclude). { username: 1, age: 0 } causes an error. Either list fields to include or list fields to exclude. _id is the exception and can be excluded separately.

Projection is like asking a print shop to copy only the name and age from a document: only the selected fields appear on the copy.


⚡ Sorting and Pagination: sort, limit, and skip

You often need to sort query results. sort() accepts an object where 1 means ascending (smallest first) and -1 means descending (largest first):

// Sort by age in descending order
db.user.find().sort({ age: -1 });

Chain sort() after find(). You can specify multiple sort fields; later fields break ties in earlier ones.

For pagination, combine limit() and skip(): limit(n) returns at most n documents, and skip(n) skips the first n. With two documents per page, page 2 means skipping two and taking two:

// Retrieve page 2 with 2 documents per page (page numbers start at 1)
db.user.find().sort({ age: -1 }).skip(2).limit(2);

This returns the second page in descending age order, after skipping the two older users. Include sort() when paginating; without a defined order, documents may be repeated or missed across pages.

skip() scans past the documents it discards, so deeper pages take longer. For larger datasets, range-based pagination is common: remember the last value on the previous page, such as age, and query the next page with { age: { $lt: lastAge } }. For now, just be aware of this approach; you can explore it when needed.

🛠 Counting Documents with countDocuments

Sometimes you only need a count, such as “N users” above a list. Use countDocuments() with a filter written just like a find() filter:

// Count users in Beijing
db.user.countDocuments({ city: 'Beijing' });

This returns 1. Pass an empty object {} to count every document in the collection:

db.user.countDocuments({});

❓ Questions and Answers

Q1: How do { city: 'Beijing' } and { city: { $in: ['Beijing'] } } differ?

For one value, they have the same effect, and equality is simpler. $in is useful for matching several values, such as { city: { $in: ['Beijing', 'Shanghai'] } }.

Q2: Does $gt: 25 include users who are 25?

No. $gt means strictly greater than; use $gte to include 25. Likewise, $lt is strictly less than, while $lte includes the boundary.

Q3: Why does my result include _id when the projection only specifies username: 1?

_id is the primary key and is included by default, even when it is absent from the inclusion list. Add _id: 0 to exclude it.

Q4: Is skip(0).limit(2) the same as limit(2)?

Yes. Skipping zero documents changes nothing. skip() is useful from page 2 onward and can be omitted on page 1.

Q5: What can go wrong if I paginate without sort()?

Without sorting, the return order is not defined. A document may appear on multiple pages, or be missed entirely. Choose a sort field before paginating.


🧪 Exercises

Run these two queries on the user collection:

  1. Find users older than 23 who do not live in Beijing. Return only username and city, excluding _id.
// Write your code here
  1. Sort by age in ascending order and retrieve page 2 with two documents per page.
// Write your code here

🎉 You can now use query filters and common operators! Next, we will explore documents and data types, including nested documents and arrays.