How to concatenate results in MongoDB?


You can concatenate results with the help of forEach(). Let us first create a collection with documents −

> db.concatenateDemo.insertOne({"Name":"John","Age":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc80dd88f9e6ff3eb0ce448")
}
> db.concatenateDemo.insertOne({"Name":"Carol","Age":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc80de18f9e6ff3eb0ce449")
}

Following is the query to display all documents from a collection with the help of find() method −

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

This will produce the following output −

{
   "_id" : ObjectId("5cc80dd88f9e6ff3eb0ce448"),
   "Name" : "John",
   "Age" : 21
}
{
   "_id" : ObjectId("5cc80de18f9e6ff3eb0ce449"),
   "Name" : "Carol",
   "Age" : 23
}

Here is the query to concatenate results −

> db.concatenateDemo.find().forEach( function (result) {result.NameAndAge = result.Name + ' ' + result.Age; printjson(result); } );

This will produce the following output −

{
   "_id" : ObjectId("5cc80dd88f9e6ff3eb0ce448"),
   "Name" : "John",
   "Age" : 21,
   "NameAndAge" : "John 21"
}
{
   "_id" : ObjectId("5cc80de18f9e6ff3eb0ce449"),
   "Name" : "Carol",
   "Age" : 23,
   "NameAndAge" : "Carol 23"
}

Updated on: 30-Jul-2019

237 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements