Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
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" }Advertisements