ifnull - Print message not found rather than null if field is null in MongoDB

You are here : Home / MongoDB Tutorial



Contents of page >
  • 1) First let's create insert documents in collection in MongoDB
  • 2) Now, Write query which display/prints firstName and salary of employee >
  • If salary of employee is null then print salaryNotFound rather than printing null.


1) First let's create insert documents in collection in MongoDB

1.1) Let's create new collection and insert document in it before finding >
db.employee.insert({id : 1,  firstName:"ank", salary : 1000 })
db.employee.insert({id : 2,  firstName:"ank", salary : null})
db.employee.insert({id : 3,  firstName:"sag", salary : 3000 })
db.employee.insert({id : 4,  firstName:"sag", salary : null})
Above will create collection (or table) (if collection already exists it will insert documents in it).

1.2) Let’s query all documents of collection using find() method>
> db.employee.find()
Output>
{ "_id" : ObjectId("58820af01e509423fa0faa73"), "id" : 1, "firstName" : "ank", "salary" : 1000 }
{ "_id" : ObjectId("58820af01e509423fa0faa74"), "id" : 2, "firstName" : "ank", "salary" : null }
{ "_id" : ObjectId("58820af01e509423fa0faa75"), "id" : 3, "firstName" : "sag", "salary" : 3000 }
{ "_id" : ObjectId("58820af11e509423fa0faa76"), "id" : 4, "firstName" : "sag", "salary" : null }



2) Now, Write query which display/prints firstName and salary of employee >
  • If salary of employee is null then print salaryNotFound rather than printing null.

We will use $ifNull operator.
db.employee.aggregate(
  [
     {
        $project: {
           firstName : 1,
           salary : { $ifNull: [ "$salary", "salaryNotFound" ] }
        }
     }
  ]
)
Output >
{ "_id" : ObjectId("58820af01e509423fa0faa73"), "firstName" : "ank", "salary" : 1000 }
{ "_id" : ObjectId("58820af01e509423fa0faa74"), "firstName" : "ank", "salary" : "salaryNotFound" }
{ "_id" : ObjectId("58820af01e509423fa0faa75"), "firstName" : "sag", "salary" : 3000 }
{ "_id" : ObjectId("58820af11e509423fa0faa76"), "firstName" : "sag", "salary" : "salaryNotFound" }

In above query >
firstName : 1 > Is used to display firstName field in output.



Summary -
So in this MongoDB tutorial we learned how to use ifnull operator - We can use it print some custom message like not found rather than printing null if field is null in MongoDB



Having any doubt? or you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter. You may join our fbGroup or linkedInGroup as well.



RELATED LINKS>

What is MongoDB - A quick introduction to database


eEdit
Must read for you :