
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 for Array Concatenation
To concatenate, use $concatArrays in MongoDB. Let us first create a collection with documents −
>db.demo14.insertOne({"ListOfStudent":["Carol","Mike","Sam"],"ListOfTeacher":["Robert","David"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e0f754bd7df943a7cec4faa") }
Following is the query to display all documents from a collection with the help of find() method −
> db.demo14.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e0f754bd7df943a7cec4faa"), "ListOfStudent" : [ "Carol", "Mike", "Sam" ], "ListOfTeacher" : [ "Robert", "David" ] }
Following is the query to concatenate array −
> db.demo14.aggregate([ ... { "$project": { ... "ListOfPeople": { "$concatArrays": [ "$ListOfStudent", "$ListOfTeacher" ] } ... }} ... ]);
This will produce the following output −
{ "_id" : ObjectId("5e0f754bd7df943a7cec4faa"), "ListOfPeople" : [ "Carol", "Mike", "Sam", "Robert", "David" ] }
Advertisements