 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB query to select one field if the other is null?
To select one field if the other is null, use $ifNull. Let us create a collection with documents −
> db.demo182.insertOne({"FirstName":"Chris","LastName":null}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e398ea19e4f06af55199802") } > db.demo182.insertOne({"FirstName":null,"LastName":"Miller"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e398ead9e4f06af55199803") } > > db.demo182.insertOne({"FirstName":"John","LastName":"Smith"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e398ebf9e4f06af55199804") } Display all documents from a collection with the help of find() method −
> db.demo182.find();
This will produce the following output −
{ "_id" : ObjectId("5e398ea19e4f06af55199802"), "FirstName" : "Chris", "LastName" : null } { "_id" : ObjectId("5e398ead9e4f06af55199803"), "FirstName" : null, "LastName" : "Miller" } { "_id" : ObjectId("5e398ebf9e4f06af55199804"), "FirstName" : "John", "LastName" : "Smith" } Following is the query to select one field if the other is null −
> db.demo182.aggregate([ ...   { ...      $project: { ...         "item": 1, ...         "Result": { "$ifNull": [ "$FirstName", "$LastName" ] } ...      } ...   } ...]) This will produce the following output −
{ "_id" : ObjectId("5e398ea19e4f06af55199802"), "Result" : "Chris" } { "_id" : ObjectId("5e398ead9e4f06af55199803"), "Result" : "Miller" } { "_id" : ObjectId("5e398ebf9e4f06af55199804"), "Result" : "John" }Advertisements
 