Conditional $first in MongoDB aggregation ignoring NULL?

To get the first non-NULL value in MongoDB aggregation, use the $match operator to filter out NULL values before applying $first in the $group stage.

Syntax

db.collection.aggregate([
    { $match: { "fieldName": { $ne: null } } },
    { $group: { 
        "_id": "$groupField", 
        "result": { $first: "$fieldName" } 
    }}
]);

Sample Data

db.conditionalFirstDemo.insertMany([
    {_id:100, "StudentName":"Chris", "StudentSubject":null},
    {_id:101, "StudentName":"Chris", "StudentSubject":null},
    {_id:102, "StudentName":"Chris", "StudentSubject":"MongoDB"},
    {_id:103, "StudentName":"Chris", "StudentSubject":"MongoDB"},
    {_id:104, "StudentName":"Chris", "StudentSubject":null}
]);

Display all documents to see the data ?

db.conditionalFirstDemo.find();
{ "_id" : 100, "StudentName" : "Chris", "StudentSubject" : null }
{ "_id" : 101, "StudentName" : "Chris", "StudentSubject" : null }
{ "_id" : 102, "StudentName" : "Chris", "StudentSubject" : "MongoDB" }
{ "_id" : 103, "StudentName" : "Chris", "StudentSubject" : "MongoDB" }
{ "_id" : 104, "StudentName" : "Chris", "StudentSubject" : null }

Example: Get First Non-NULL Value

Get the first non-NULL StudentSubject for each student ?

db.conditionalFirstDemo.aggregate([
    { "$match": { "StudentSubject": { "$ne": null } } },
    { "$group": { 
        "_id": "$StudentName", 
        "StudentSubject": { "$first": "$StudentSubject" } 
    }}
]);
{ "_id" : "Chris", "StudentSubject" : "MongoDB" }

How It Works

  • $match filters documents where StudentSubject is not null
  • $group groups by StudentName and takes the first non-null value
  • $first returns the first value from the filtered (non-null) results

Conclusion

Use $match with $ne: null before $group to ensure $first operates only on non-NULL values. This effectively gets the first valid value while ignoring NULL entries.

Updated on: 2026-03-15T01:07:36+05:30

624 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements