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
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
-
$matchfilters documents whereStudentSubjectis not null -
$groupgroups byStudentNameand takes the first non-null value -
$firstreturns 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.
Advertisements
