

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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" }
- Related Questions & Answers
- How to concatenate MySQL distinct query results into a string?
- How to print results of script in MongoDB?
- Concatenate fields in MongoDB?
- Concatenate with condition in MongoDB?
- Perform MongoDB array concatenation to concatenate records
- Getting MongoDB results from the previous month
- Push query results into variable with MongoDB?
- How to PIVOT results in Oracle?
- How to UNPIVOT results in Oracle?
- How to merge MySQL results?
- How to get tag count in MongoDB query results based on list of names?
- Is there a MongoDB query to concatenate deep sub-lists?
- MongoDB query to concatenate values of array with other fields
- How can I concatenate an array of integer in MongoDB aggregation method?
- How to concatenate lists in java?
Advertisements