Mongooseによるデータのクエリとフィルタリング
基本的なCRUDの先に進み、フィルター、演算子、並べ替え、ページネーション、プロジェクションを使ってMongooseで高度なクエリを構築する方法を学びます。
「Mongooseによるデータのクエリとフィルタリング」はCoddyKit上の無料Node.js Backend Development Bootcampレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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によるデータのクエリとフィルタリング」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Node.js Backend Development Bootcampコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Node.js Backend Development Bootcampコースには全4レッスンが含まれています。
「Mongooseによるデータのクエリとフィルタリング」で何を学びますか?
基本的なCRUDの先に進み、フィルター、演算子、並べ替え、ページネーション、プロジェクションを使ってMongooseで高度なクエリを構築する方法を学びます。 ブラウザで直接実行するハンズオンコードでNode.js Backend Development Bootcampを演習し、24時間対応の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によるデータのクエリとフィルタリング