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 apply a condition only if field exists in MongoDB?
To apply a condition only if a field exists in MongoDB, use the $or operator combined with $exists. This allows you to match documents where a field either doesn't exist or meets a specific condition.
Syntax
db.collection.find({
$or: [
{ fieldName: { $exists: false } },
{ fieldName: condition }
]
});
Sample Data
Let's create a collection with some documents where the StudentAge field is missing in one document ?
db.applyConditionDemo.insertMany([
{ "StudentName": "Larry", "StudentAge": 21, "StudentMarks": 45 },
{ "StudentName": "Sam", "StudentAge": 23, "StudentMarks": 55 },
{ "StudentName": "David", "StudentAge": 21, "StudentMarks": 65 },
{ "StudentName": "Carol", "StudentAge": 24, "StudentMarks": 78 },
{ "StudentName": "Chris", "StudentAge": 21, "StudentMarks": 88 },
{ "StudentName": "Robert", "StudentMarks": 98 }
]);
Display all documents to see the structure ?
db.applyConditionDemo.find().pretty();
{
"_id" : ObjectId("5cb80b78623186894665ae36"),
"StudentName" : "Larry",
"StudentAge" : 21,
"StudentMarks" : 45
}
{
"_id" : ObjectId("5cb80b87623186894665ae37"),
"StudentName" : "Sam",
"StudentAge" : 23,
"StudentMarks" : 55
}
{
"_id" : ObjectId("5cb80b95623186894665ae38"),
"StudentName" : "David",
"StudentAge" : 21,
"StudentMarks" : 65
}
{
"_id" : ObjectId("5cb80ba3623186894665ae39"),
"StudentName" : "Carol",
"StudentAge" : 24,
"StudentMarks" : 78
}
{
"_id" : ObjectId("5cb80bae623186894665ae3a"),
"StudentName" : "Chris",
"StudentAge" : 21,
"StudentMarks" : 88
}
{
"_id" : ObjectId("5cb80c3d623186894665ae3b"),
"StudentName" : "Robert",
"StudentMarks" : 98
}
Example: Apply Condition Only If Field Exists
Find all documents where StudentAge is 21 OR the field doesn't exist at all ?
db.applyConditionDemo.find({
$or: [
{ StudentAge: { $exists: false } },
{ StudentAge: 21 }
]
}).pretty();
{
"_id" : ObjectId("5cb80b78623186894665ae36"),
"StudentName" : "Larry",
"StudentAge" : 21,
"StudentMarks" : 45
}
{
"_id" : ObjectId("5cb80b95623186894665ae38"),
"StudentName" : "David",
"StudentAge" : 21,
"StudentMarks" : 65
}
{
"_id" : ObjectId("5cb80bae623186894665ae3a"),
"StudentName" : "Chris",
"StudentAge" : 21,
"StudentMarks" : 88
}
{
"_id" : ObjectId("5cb80c3d623186894665ae3b"),
"StudentName" : "Robert",
"StudentMarks" : 98
}
How It Works
-
{ StudentAge: { $exists: false } }matches documents whereStudentAgefield is not present -
{ StudentAge: 21 }matches documents whereStudentAgeequals 21 -
$orcombines both conditions, returning documents that satisfy either condition
Conclusion
Use $or with $exists: false to apply conditions only when fields exist. This technique helps handle documents with inconsistent schema structures effectively.
Advertisements
