MongoDB query to concatenate values of array with other fields



To concatenate in MongoDB, use $concat in $project. Let us create a collection with documents −

> db.demo359.insertOne( ...    { ... ...       Name1: "Chris", ...       Name2: "David", ...       Subjects: ["MySQL","MongoDB","Java"] ...    } ... ); {    "acknowledged" : true,    "insertedId" : ObjectId("5e5694cdf8647eb59e5620d0") }

Display all documents from a collection with the help of find() method −

> db.demo359.find().pretty();

This will produce the following output −

{    "_id" : ObjectId("5e5694cdf8647eb59e5620d0"),    "Name1" : "Chris",    "Name2" : "David",    "Subjects" : [       "MySQL",       "MongoDB",       "Java"    ] }

Following is the query to concatenate values of the array with other fields −

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

This will produce the following output −

{ "_id" : ObjectId("5e5694cdf8647eb59e5620d0"), "ConcatResult" : "Chris MySQL MongoDB Java" }
Updated on: 2020-04-02T08:20:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements