Conditional $first in MongoDB aggregation ignoring NULL?


You can use $match operator under aggregate() to get the first record. Let us first create a collection with documents −

> db.conditionalFirstDemo.insertOne({_id:100,"StudentName":"Chris","StudentSubject":null});
{ "acknowledged" : true, "insertedId" : 100 }
> db.conditionalFirstDemo.insertOne({_id:101,"StudentName":"Chris","StudentSubject":null});
{ "acknowledged" : true, "insertedId" : 101 }
>db.conditionalFirstDemo.insertOne({_id:102,"StudentName":"Chris","StudentSubject":"MongoDB"});
{ "acknowledged" : true, "insertedId" : 102 }
>db.conditionalFirstDemo.insertOne({_id:103,"StudentName":"Chris","StudentSubject":"MongoDB"});
{ "acknowledged" : true, "insertedId" : 103 }
> db.conditionalFirstDemo.insertOne({_id:104,"StudentName":"Chris","StudentSubject":null});
{ "acknowledged" : true, "insertedId" : 104 }

Following is the query to display all documents from a collection with the help of find() method −

> db.conditionalFirstDemo.find();

This will produce the following output −

{ "_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 }

Following is the query to conditional $first in MongoDB aggregation −

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

This will produce the following output −

{ "_id" : "Chris", "StudentSubject" : "MongoDB" }

Updated on: 30-Jul-2019

356 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements