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
Implement a MongoDB $cond field in a projection pipeline based on the presence or absence of a field?
To implement a MongoDB $cond field in a projection pipeline based on the presence or absence of a field, use $cond along with $anyElementTrue. NULL values (absence of a field) evaluate to FALSE, and empty arrays also return FALSE with $anyElementTrue.
Syntax
db.collection.aggregate([
{
"$project": {
"fieldName": {
"$cond": [
{ "$anyElementTrue": [ [ "$sourceField" ] ] },
"valueIfPresent",
"valueIfAbsent"
]
}
}
}
]);
Sample Data
Let us create a collection with documents ?
db.presenceDemo.insertMany([
{ "StudentName": null },
{ "StudentName": "Chris" },
{ "StudentName": null },
{ "StudentName": "David" }
]);
Following is the query to display all documents from the collection ?
db.presenceDemo.find();
{ "_id": ObjectId("..."), "StudentName": null }
{ "_id": ObjectId("..."), "StudentName": "Chris" }
{ "_id": ObjectId("..."), "StudentName": null }
{ "_id": ObjectId("..."), "StudentName": "David" }
Example: Check Field Presence
Here is the query to implement a $cond field based on the presence or absence of a field ?
db.presenceDemo.aggregate([
{
"$project": {
"MyValue": {
"$cond": [
{ "$anyElementTrue": [ [ "$StudentName" ] ] },
1,
0
]
}
}
}
]);
{ "_id": ObjectId("..."), "MyValue": 0 }
{ "_id": ObjectId("..."), "MyValue": 1 }
{ "_id": ObjectId("..."), "MyValue": 0 }
{ "_id": ObjectId("..."), "MyValue": 1 }
How It Works
-
$anyElementTruewraps the field in an array and checks if any element is truthy - NULL values and missing fields evaluate to FALSE
-
$condreturns the first value (1) if the condition is TRUE, otherwise the second value (0)
Conclusion
Use $cond with $anyElementTrue to conditionally project fields based on field presence. This technique effectively handles NULL values and missing fields in MongoDB aggregation pipelines.
Advertisements
