Beyond simple value comparisons, enterprise querying requires compound Boolean logic, schema existence checks, and precise array pattern matching. MongoDB provides robust Logical, Element, and Array query operators.
1. Logical Query Operators: $and, $or, $nor, $not
$or: Matches documents that satisfy at least one condition:
1// Find courses that are either free (price: 0) OR have a top rating (>= 4.8)
2const featured =await db.collection('courses').find({
3$or:[
4{price:0},
5{rating:{$gte:4.8}}
6]
7}).toArray();
$and: Explicit Boolean AND. While specifying multiple fields in a filter object implicitly applies AND, $and is required when targeting the same field with multiple complex conditions or combining multiple $or clauses:
1const query =await db.collection('users').find({
2$and:[
3{$or:[{role:'admin'},{role:'moderator'}]},
4{$or:[{isActive:true},{isSuperUser:true}]}
5]
6}).toArray();
2. Element Operators: $exists & $type
Because MongoDB is schema-flexible, documents within the same collection may contain different fields:
$exists: Checks if a field is present in the document.
1// Find all users who have an optional 'phoneNumber' field