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

  • $anyElementTrue wraps the field in an array and checks if any element is truthy
  • NULL values and missing fields evaluate to FALSE
  • $cond returns 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.

Updated on: 2026-03-15T02:05:31+05:30

317 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements