Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Implement MongoDB $concatArrays even when some of the values are null?
Use the $ifNull operator with $concatArrays in the aggregation framework to concatenate arrays even when some fields are null or missing. The $ifNull operator replaces null values with an empty array, allowing concatenation to proceed successfully.
Syntax
db.collection.aggregate([
{
$project: {
concatenatedField: {
$concatArrays: [
{ $ifNull: ["$array1", []] },
{ $ifNull: ["$array2", []] }
]
}
}
}
]);
Sample Data
db.concatenateArraysDemo.insertMany([
{
"FirstSemesterSubjects": ["MongoDB", "MySQL", "Java"],
"SecondSemesterSubjects": ["C", "C++"]
},
{
"FirstSemesterSubjects": ["C#", "Ruby", "Python"]
},
{
"FirstSemesterSubjects": ["HTML", "CSS", "Javascript"],
"SecondSemesterSubjects": ["CSS", "Javascript"]
}
]);
Example: Concatenate Arrays with Null Handling
The following query concatenates arrays even when SecondSemesterSubjects is null or missing ?
db.concatenateArraysDemo.aggregate([
{
$project: {
ConcatenateArrays: {
$concatArrays: [
{ $ifNull: ["$FirstSemesterSubjects", []] },
{ $ifNull: ["$SecondSemesterSubjects", []] }
]
}
}
}
]);
{ "_id" : ObjectId("5cd687707924bb85b3f4895c"), "ConcatenateArrays" : [ "MongoDB", "MySQL", "Java", "C", "C++" ] }
{ "_id" : ObjectId("5cd687927924bb85b3f4895d"), "ConcatenateArrays" : [ "C#", "Ruby", "Python" ] }
{ "_id" : ObjectId("5cd687bb7924bb85b3f4895e"), "ConcatenateArrays" : [ "HTML", "CSS", "Javascript", "CSS", "Javascript" ] }
How It Works
-
$ifNullchecks if the field is null or missing - If null/missing, it returns an empty array
[]as the fallback -
$concatArraysthen concatenates the arrays (including empty ones) - Documents with missing fields still participate in concatenation
Conclusion
The $ifNull operator ensures that $concatArrays works reliably even with null or missing array fields. This combination prevents aggregation errors and provides consistent array concatenation results across all documents.
Advertisements
