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
Perform MongoDB array concatenation to concatenate records
For array concatenation, use $concatArrays operator. Let us first create a collection with documents −
>db.arrayConcatenationDemo.insertOne({"TeacherName":["Chris","Robert"],"StudentName":["Mike","Sam"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ce921c078f00858fb12e911")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.arrayConcatenationDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5ce921c078f00858fb12e911"),
"TeacherName" : [
"Chris",
"Robert"
],
"StudentName" : [
"Mike",
"Sam"
]
}
Following is the query for array concatenation −
> db.arrayConcatenationDemo.aggregate([
{ "$project": {
"StudentAndTeacherName": { "$concatArrays": [ "$TeacherName", "$StudentName" ] }
}}
]);
This will produce the following output −
{ "_id" : ObjectId("5ce921c078f00858fb12e911"), "StudentAndTeacherName" : [ "Chris", "Robert", "Mike", "Sam" ] }Advertisements