To concatenate fields, use the $concat operator. Let us first create a collection with documents −
>db.concatenateFieldsDemo.insertOne({"StudentFirstName":"Adam","StudentLastName":"Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6ebf46d78f205348bc62e") } >db.concatenateFieldsDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Doe"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6ebfc6d78f205348bc62f") } >db.concatenateFieldsDemo.insertOne({"StudentFirstName":"David","StudentLastName":"Miller"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6ec376d78f205348bc630") } >db.concatenateFieldsDemo.insertOne({"StudentFirstName":"Sam","StudentLastName":"Williams"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6ec436d78f205348bc631") }
Following is the query to display all documents from a collection with the help of find() method −
> db.concatenateFieldsDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd6ebf46d78f205348bc62e"), "StudentFirstName" : "Adam", "StudentLastName" : "Smith" } { "_id" : ObjectId("5cd6ebfc6d78f205348bc62f"), "StudentFirstName" : "John", "StudentLastName" : "Doe" } { "_id" : ObjectId("5cd6ec376d78f205348bc630"), "StudentFirstName" : "David", "StudentLastName" : "Miller" } { "_id" : ObjectId("5cd6ec436d78f205348bc631"), "StudentFirstName" : "Sam", "StudentLastName" : "Williams" }
Following is the query to select and concatenate fields −
> db.concatenateFieldsDemo.aggregate([ {$project:{"StudentFullName":{$concat: ["$StudentFirstName","/","$StudentLastName"]},"StudentFirstName":1,"StudentLastName":1}} ]);
This will produce the following output −
{ "_id" : ObjectId("5cd6ebf46d78f205348bc62e"), "StudentFirstName" : "Adam", "StudentLastName" : "Smith", "StudentFullName" : "Adam/Smith" } { "_id" : ObjectId("5cd6ebfc6d78f205348bc62f"), "StudentFirstName" : "John", "StudentLastName" : "Doe", "StudentFullName" : "John/Doe" } { "_id" : ObjectId("5cd6ec376d78f205348bc630"), "StudentFirstName" : "David", "StudentLastName" : "Miller", "StudentFullName" : "David/Miller" } { "_id" : ObjectId("5cd6ec436d78f205348bc631"), "StudentFirstName" : "Sam", "StudentLastName" : "Williams", "StudentFullName" : "Sam/Williams" }