この章では、MongoDBの論理演算子について紹介します。これは、SQLの「and」と「or」と同様の条件を満たすものです。
MongoDBでサポートされている論理演算子
演算子 | 説明 |
---|---|
$and | SQLの「and」と同様に、すべての指定条件を満たすドキュメントに一致します |
$not | 指定された式に対して論理的なNOT演算を実行します |
$or | SQLの「or」と同様に、指定された条件の少なくとも1つを満たすドキュメントに一致します |
$nor | 指定された両方の条件を満たさないドキュメントに一致します |
$and
構文:
{ $and: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }
説明:
-
はサブ式です - $and はサブ式のグループを含む配列を取り、すべてのサブ式を満たさなければなりません
例:
db.inventory.find( { $and: [ { qty: { $lt : 10 } }, { qty : { $gt: 50 } }] } )
同等のSQL:
select * from inventory where qty > 50 and qty < 10
$not
db.inventory.find( { price: { $not: { $gt: 1.99 } } } )
説明:
- 条件が price > 1.99 の場合、NOT演算は price <= 1.99 になります。
- これは、price が 1.99 以下のドキュメントまたは price フィールドが存在しないドキュメントをクエリすることを意味します。
SQLと同様:
select * from inventory where price <= 1.99
$or
SQLの「or」と同様の条件を満たします 構文:
{ $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }
説明:
-
はサブ式です - $or は、少なくとも1つのサブ式を満たすサブ式のグループを含む配列を取ります
例:
db.inventory.find( { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] } )
同等のSQL:
select * from inventory where quantity < 20 or price=10
$nor
論理的なNOR演算 構文:
{ $nor: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }
例:
db.inventory.find( { $nor: [ { price: 1.99 }, { sale: true } ] } )
説明:
- price != 1.99 かつ sale != true、または
- price != 1.99 かつ sale フィールドが存在しない、または
- price フィールドが存在せず、sale != true