MongoDB query to select one field if the other is null and the first field if both are not null?

In MongoDB, to select one field when another is null and the first field when both are not null, use the $ifNull operator in an aggregation pipeline. This operator returns the first non-null value from the provided expressions.

Syntax

db.collection.aggregate([
    {
        $project: {
            "fieldName": { "$ifNull": [ "$primaryField", "$fallbackField" ] }
        }
    }
]);

Sample Data

Let us first create a collection with documents ?

db.querySelectDemo.insertMany([
    {"Value1": 10, "Value2": null},
    {"Value1": null, "Value2": 30},
    {"Value1": 60, "Value2": 40}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cefc0ceef71edecf6a1f6b6"),
        ObjectId("5cefc0d7ef71edecf6a1f6b7"),
        ObjectId("5cefc0e2ef71edecf6a1f6b8")
    ]
}

Display all documents from the collection ?

db.querySelectDemo.find().pretty();
{
    "_id": ObjectId("5cefc0ceef71edecf6a1f6b6"),
    "Value1": 10,
    "Value2": null
}
{
    "_id": ObjectId("5cefc0d7ef71edecf6a1f6b7"),
    "Value1": null,
    "Value2": 30
}
{
    "_id": ObjectId("5cefc0e2ef71edecf6a1f6b8"),
    "Value1": 60,
    "Value2": 40
}

Example: Using $ifNull Operator

The following query selects Value1 if it's not null, otherwise selects Value2 ?

db.querySelectDemo.aggregate([
    {
        $project: {
            "Value1": { "$ifNull": [ "$Value1", "$Value2" ] }
        }
    }
]);
{ "_id": ObjectId("5cefc0ceef71edecf6a1f6b6"), "Value1": 10 }
{ "_id": ObjectId("5cefc0d7ef71edecf6a1f6b7"), "Value1": 30 }
{ "_id": ObjectId("5cefc0e2ef71edecf6a1f6b8"), "Value1": 60 }

How It Works

  • Document 1: Value1 (10) is not null, so it returns 10
  • Document 2: Value1 is null, so it returns Value2 (30)
  • Document 3: Value1 (60) is not null, so it returns 60 (ignores Value2)

Conclusion

The $ifNull operator provides a clean way to handle null values by selecting the first non-null field from a list of expressions. This is particularly useful for creating fallback logic in data projection scenarios.

Updated on: 2026-03-15T01:27:33+05:30

496 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements