MongoDB Query to Find Documents with Multiple Conditions
db.collection.find({ field1: value1, field2: value2 }) to find documents matching multiple conditions with AND logic in MongoDB.Examples
How to Think About It
find query object. So, you just add each condition as a key-value pair inside the query.Algorithm
Code
db.users.insertMany([
{ _id: 1, name: 'Alice', age: 25, city: 'New York' },
{ _id: 2, name: 'Bob', age: 30, city: 'Chicago', status: 'active', score: 90 },
{ _id: 3, name: 'Carol', age: 25, city: 'New York', status: 'inactive' }
]);
const query = { age: 25, city: 'New York' };
const results = db.users.find(query).toArray();
printjson(results);Dry Run
Let's trace the query { age: 25, city: 'New York' } through the find operation.
Start with all documents
[{_id:1, age:25, city:'New York'}, {_id:2, age:30, city:'Chicago'}, {_id:3, age:25, city:'New York'}]
Filter by age: 25
[{_id:1, age:25, city:'New York'}, {_id:3, age:25, city:'New York'}]
Filter by city: 'New York'
[{_id:1, age:25, city:'New York'}, {_id:3, age:25, city:'New York'}]
| Step | Documents After Filter |
|---|---|
| 1 | [{_id:1, age:25, city:'New York'}, {_id:2, age:30, city:'Chicago'}, {_id:3, age:25, city:'New York'}] |
| 2 | [{_id:1, age:25, city:'New York'}, {_id:3, age:25, city:'New York'}] |
| 3 | [{_id:1, age:25, city:'New York'}, {_id:3, age:25, city:'New York'}] |
Why This Works
Step 1: Multiple conditions in one object
MongoDB treats multiple key-value pairs inside the find query as AND conditions, so all must be true for a document to match.
Step 2: Filtering documents
The database checks each document to see if it meets every condition in the query object.
Step 3: Returning matched documents
Only documents that satisfy all conditions are returned in the result set.
Alternative Approaches
db.users.find({ $and: [ { age: 25 }, { city: 'New York' } ] }).toArray();db.users.find({ $or: [ { age: 25 }, { city: 'New York' } ] }).toArray();Complexity: O(n) time, O(k) space
Time Complexity
The query scans documents in the collection; time grows linearly with the number of documents (n).
Space Complexity
Space depends on the number of matched documents (k) returned; query object size is minimal.
Which Approach is Fastest?
Using a simple query object with multiple conditions is fastest and most readable for AND logic; $and operator is equivalent but more verbose.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple query object | O(n) | O(k) | Most common AND queries, simple and fast |
| $and operator | O(n) | O(k) | Complex queries needing explicit AND, same performance |
| $or operator | O(n) | O(k) | Queries needing OR logic, different use case |
find query object to combine them with AND logic easily.find calls instead of combining conditions in one query object.