使用 Mongoose 查询与筛选数据
超越基础 CRUD,学习如何在 Mongoose 中使用筛选器、运算符、排序、分页和投影构建强大的查询。
使用 Mongoose 查询与筛选数据 是 CoddyKit 上的免费 Node.js Backend Development Bootcamp 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Node.js Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Node.js Backend Development Bootcamp 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Beyond Find-All
Fetching every document with Model.find() works for tiny collections, but real apps need to filter, sort, limit, and shape their results.
Mongoose gives you a fluent query API that mirrors MongoDB's query language.
const users = await User.find({ active: true });Filtering by Field
Pass an object to find() to match documents by exact field values. Multiple keys are combined with logical AND.
const admins = await User.find({ role: 'admin', active: true });Comparison Operators
MongoDB operators start with $. The most common comparisons are:
$gt/$gtegreater than (or equal)$lt/$lteless than (or equal)$nenot equal
const adults = await User.find({ age: { $gte: 18 } });Matching Multiple Values
Use $in to match any value from a list, and $nin to exclude a list. This is cleaner than chaining many OR conditions.
const team = await User.find({ role: { $in: ['admin', 'editor'] } });Logical OR
The $or operator takes an array of conditions; a document matches if any one is true.
const results = await User.find({
$or: [{ city: 'Berlin' }, { city: 'Paris' }]
});Sorting Results
Chain .sort() to order results. Use 1 for ascending and -1 for descending. You can sort by multiple fields.
const recent = await User.find().sort({ createdAt: -1, name: 1 });Limiting and Skipping
Pagination relies on .limit() (max documents) and .skip() (how many to bypass). For page 2 with 10 per page, skip 10 and limit 10.
const page = 2, perPage = 10;
const items = await User.find()
.skip((page - 1) * perPage)
.limit(perPage);Selecting Specific Fields
Use .select() (projection) to return only the fields you need. Prefix a field with - to exclude it. This reduces payload size and hides sensitive data.
const safe = await User.find().select('name email -_id');
const noPass = await User.find().select('-password');Finding a Single Document
findOne() returns the first match or null. findById() is a shortcut for matching by _id.
const user = await User.findOne({ email: 'a@b.com' });
const byId = await User.findById('652f1c...');Counting Documents
To know how many documents match a filter without fetching them all, use countDocuments(). This is essential for showing total pages in pagination.
const total = await User.countDocuments({ active: true });
console.log('Active users:', total);Text & Regex Search
For partial matches, use a regular expression. The $regex operator with the i option makes a case-insensitive search.
const matches = await User.find({
name: { $regex: 'an', $options: 'i' }
});Quick Check
Test your Mongoose querying skills.
Recap
You can now build rich Mongoose queries:
- Filter by field and combine with operators like
$gte,$in,$or - Order results with
.sort() - Paginate with
.skip()and.limit() - Shape output with
.select() - Count matches with
countDocuments()
These tools turn a basic data layer into a flexible, production-ready API.
常见问题解答
「使用 Mongoose 查询与筛选数据」课时是免费的吗?
是的 — 「使用 Mongoose 查询与筛选数据」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Node.js Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 Node.js Backend Development Bootcamp 课程共包含 4 节课。
「使用 Mongoose 查询与筛选数据」这节课中我会学到什么?
超越基础 CRUD,学习如何在 Mongoose 中使用筛选器、运算符、排序、分页和投影构建强大的查询。 你通过在浏览器中直接运行的动手代码来练习 Node.js Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Node.js Backend Development Bootcamp 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Node.js Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「使用 Mongoose 查询与筛选数据」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Node.js Backend Development Bootcamp 课中编写并运行代码吗?
能。每节 Node.js Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 将 Node.js 连接到 MongoDB
- 用于数据建模的 Mongoose ODM
- 使用 Mongoose 执行 CRUD 操作
- 使用 Mongoose 查询与筛选数据