MongoDB query to concatenate values of array with other fields

MongoDBDatabaseBig Data Analytics

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" }
raja
Published on 02-Apr-2020 08:20:25
Advertisements