Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to find MongoDB documents in a collection with a filter on multiple combined fields?
To find MongoDB documents with filters on multiple combined fields, use the $or or $and operators within the find() method. These operators allow you to combine multiple conditions across different fields.
Syntax
// OR operator - matches documents that satisfy ANY condition
db.collection.find({
$or: [
{ "field1": condition1 },
{ "field2": condition2 }
]
});
// AND operator - matches documents that satisfy ALL conditions
db.collection.find({
$and: [
{ "field1": condition1 },
{ "field2": condition2 }
]
});
Sample Data
db.findDocumentWithFilterDemo.insertMany([
{"ClientName": "Robert", "IsMarried": false},
{"ClientName": "Chris", "IsMarried": true},
{"ClientName": "David", "IsMarried": true},
{"ClientName": "Carol", "IsMarried": true}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd4fd1e2cba06f46efe9ef1"),
ObjectId("5cd4fd322cba06f46efe9ef2"),
ObjectId("5cd4fd3b2cba06f46efe9ef3"),
ObjectId("5cd4fd452cba06f46efe9ef4")
]
}
Method 1: Using $or Operator
Find documents where ClientName is NOT "Robert" OR IsMarried is NOT false ?
db.findDocumentWithFilterDemo.find({
$or: [
{ "ClientName": { $ne: "Robert" } },
{ "IsMarried": { $ne: false } }
]
});
{ "_id": ObjectId("5cd4fd322cba06f46efe9ef2"), "ClientName": "Chris", "IsMarried": true }
{ "_id": ObjectId("5cd4fd3b2cba06f46efe9ef3"), "ClientName": "David", "IsMarried": true }
{ "_id": ObjectId("5cd4fd452cba06f46efe9ef4"), "ClientName": "Carol", "IsMarried": true }
Method 2: Using $and Operator
Find documents where ClientName starts with "C" AND IsMarried is true ?
db.findDocumentWithFilterDemo.find({
$and: [
{ "ClientName": { $regex: "^C" } },
{ "IsMarried": true }
]
});
{ "_id": ObjectId("5cd4fd322cba06f46efe9ef2"), "ClientName": "Chris", "IsMarried": true }
{ "_id": ObjectId("5cd4fd452cba06f46efe9ef4"), "ClientName": "Carol", "IsMarried": true }
Key Points
-
$orreturns documents matching any of the specified conditions -
$andreturns documents matching all of the specified conditions - Both operators accept an array of condition objects
- You can combine multiple field conditions within each operator
Conclusion
Use $or for inclusive filtering and $and for restrictive filtering when working with multiple field conditions. These operators provide powerful ways to query MongoDB collections based on complex criteria across different document fields.
Advertisements
