Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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 and the first field if both are not null?
For this, use $ifNull operator
Let us first create a collection with documents −
> dbquerySelectDemoinsertOne({"Value1":10,"Value2":null});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cefc0ceef71edecf6a1f6b6")
}
> dbquerySelectDemoinsertOne({"Value1":null,"Value2":30});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cefc0d7ef71edecf6a1f6b7")
}
> dbquerySelectDemoinsertOne({"Value1":60,"Value2":40});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cefc0e2ef71edecf6a1f6b8")
}
Display all documents from a collection with the help of find() method −
> dbquerySelectDemofind()pretty();
Output
{
"_id" : ObjectId("5cefc0ceef71edecf6a1f6b6"),
"Value1" : 10,
"Value2" : null
}
{
"_id" : ObjectId("5cefc0d7ef71edecf6a1f6b7"),
"Value1" : null,
"Value2" : 30
}
{
"_id" : ObjectId("5cefc0e2ef71edecf6a1f6b8"),
"Value1" : 60,
"Value2" : 40
}
Following is the query to select one field if other is null −
> dbquerySelectDemoaggregate([
{
$project: {
"Value1": { "$ifNull": [ "$Value1", "$Value2" ] }
}
}
]);
Output
{ "_id" : ObjectId("5cefc0ceef71edecf6a1f6b6"), "Value1" : 10 }
{ "_id" : ObjectId("5cefc0d7ef71edecf6a1f6b7"), "Value1" : 30 }
{ "_id" : ObjectId("5cefc0e2ef71edecf6a1f6b8"), "Value1" : 60 }
Advertisements