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
Working with MongoDB $concatArrays in $project on existing multi-array field
The $concatArrays is used to concatenate arrays to return the concatenated array.
Let us create a collection with documents −
> db.demo338.insertOne({"Name":"Chris","Marks1":[ [56,67,45],[67,89,90,91]]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e5299baf8647eb59e56209f")
}
Display all documents from a collection with the help of find() method −
> db.demo338.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e5299baf8647eb59e56209f"),
"Name" : "Chris",
"Marks1" : [
[
56,
67,
45
],
[
67,
89,
90,
91
]
]
}
Following is the query to work on the existing multi-array field and concatenate arrays −
> db.demo338.aggregate([
... { "$project": {
... "Marks": {
... "$reduce": {
... "input": "$Marks1",
... "initialValue": [],
... "in": { "$concatArrays": ["$$this", "$$value"] }
... }
... }
... }}
... ])
This will produce the following output &minus'
{ "_id" : ObjectId("5e5299baf8647eb59e56209f"), "Marks" : [ 67, 89, 90, 91, 56, 67, 45 ] }Advertisements