- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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