- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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" }
Advertisements