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
MongoDB query to concatenate values of array with other fields
To concatenate values of an array with other fields in MongoDB, use $reduce to convert the array into a single string, then $concat to combine it with other fields in the $project stage.
Syntax
db.collection.aggregate([
{
$project: {
arrayAsString: {
$reduce: {
input: "$arrayField",
initialValue: "",
in: { $concat: ["$$value", " ", "$$this"] }
}
},
otherField: 1
}
},
{
$project: {
result: { $concat: ["$otherField", "$arrayAsString"] }
}
}
])
Sample Data
db.demo359.insertOne({
Name1: "Chris",
Name2: "David",
Subjects: ["MySQL", "MongoDB", "Java"]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e5694cdf8647eb59e5620d0")
}
Display the document to verify the structure ?
db.demo359.find().pretty();
{
"_id": ObjectId("5e5694cdf8647eb59e5620d0"),
"Name1": "Chris",
"Name2": "David",
"Subjects": [
"MySQL",
"MongoDB",
"Java"
]
}
Example: Concatenate Array with Name Field
Concatenate the Name1 field with all Subjects array values ?
db.demo359.aggregate([
{
$project: {
values: {
$reduce: {
input: "$Subjects",
initialValue: "",
in: {
$concat: ["$$value", " ", "$$this"]
}
}
},
Name1: 1
}
},
{
$project: {
ConcatResult: { $concat: ["$Name1", "$values"] }
}
}
])
{ "_id": ObjectId("5e5694cdf8647eb59e5620d0"), "ConcatResult": "Chris MySQL MongoDB Java" }
How It Works
-
$reduceiterates through the array and builds a single concatenated string -
initialValue: ""starts with an empty string -
$$valueis the accumulated result,$$thisis the current array element - The second
$projectcombines the string result with other fields using$concat
Conclusion
Use $reduce to convert arrays into concatenated strings, then $concat to combine with other fields. This approach handles arrays of any length and provides flexible string formatting options.
Advertisements
