MongoDB は論理演算子 — $and、$or、$not、$nor — と、フィルタ内の複数フィールドの暗黙的AND を使用してクエリ条件を組み合わせます。これらを使うと、必要なドキュメントを正確に見つけるための複雑なクエリロジックを表現できます。
暗黙的AND(複数フィールド)
db..({ : , : { : } });
MongoDB は論理演算子 — $and、$or、$not、$nor — と、フィルタ内の複数フィールドの暗黙的AND を使用してクエリ条件を組み合わせます。これらを使うと、必要なドキュメントを正確に見つけるための複雑なクエリロジックを表現できます。
db..({ : , : { : } });
最もシンプルなケース:フィルタに複数の条件をリストすると、暗黙的にAND されます — すべての条件がマッチする必要があります。
// $or takes an array of conditions; a document matches if ANY is true
db.users.find({
$or: [
{ age: { $lt: 18 } },
{ age: { $gt: 65 } }
]
});
// → age < 18 OR age > 65
// usually implicit, but $and is needed when combining conditions on the SAME field
db.products.find({
$and: [
{ price: { $gt: 100 } },
{ price: { $lt: 500 } }
]
});
// (often you can write { price: { $gt: 100, $lt: 500 } } instead — cleaner)
// $and is also useful to combine $or groups:
db.users.find({
$and: [
{ $or: [{ role: "admin" }, { role: "editor" }] },
{ active: true }
]
});
db.products.find({ price: { $not: { $gt: 100 } } }); // NOT (price > 100) → price <= 100 or missing
db.users.find({ $nor: [{ active: true }, { premium: true }] }); // NEITHER condition true
// real queries combine logical + comparison operators
db.orders.find({
status: "shipped", // implicit AND
$or: [
{ total: { $gt: 1000 } },
{ priority: "high" }
]
});
// → status = shipped AND (total > 1000 OR priority = high)
論理演算子は MongoDB で複雑なクエリ条件を表現するために不可欠 です — 実際のクエリは単一の条件以上のもの(AND/OR ロジックで複数の条件を組み合わせることが多い)が必要なため、これらを理解することはデータを効果的にフィルタリングするための基本的な日常知識です。
複数フィルタフィールドの暗黙的AND (最もシンプルで一般的なケース — すべてマッチする必要がある条件をリストアップ)、$or (複数の条件のいずれかにマッチ — 代替案として頻繁に必要)、$and (明示的AND、同一フィールド上の条件を組み合わせるか $or 句をグループ化する場合に必要)、および $not/$nor (否定)を知ることで、クエリ要件を表現するための論理的な構成要素がカバーされます。
論理演算子と比較演算子を組み合わせる (「status shipped AND (total > 1000 OR priority high)」のようなクエリをビルド)方法を理解することは、アプリケーションが必要とする現実的な複数条件クエリに不可欠です。
複数条件でデータをフィルタリングすることは一般的なニーズ(複雑な条件にマッチするドキュメントを見つける)であり、MongoDB の論理演算子(暗黙的AND、$or、$and、$not/$nor)がこのロジックを表現する方法 — 実際の条件のための比較演算子と組み合わせて — であるため、論理演算子を理解することは効果的なクエリを作成するための不可欠で頻繁に適用される MongoDB の知識であり、SQL の WHERE 句で AND/OR/NOT をマスターすることと同等であり、実際のアプリケーションが要求する複雑な条件でドキュメントを正確に見つけるために必要です。