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 ] }

Updated on: 02-Apr-2020

243 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements