Prepend string to entire column in MongoDB using aggregate framework. Let us first create a collection with documents −
> db.prependDemo.insertOne({"StudentFirstName":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5ccf3bcedceb9a92e6aa1955") } > db.prependDemo.insertOne({"StudentFirstName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5ccf3bd3dceb9a92e6aa1956") } > db.prependDemo.insertOne({"StudentFirstName":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5ccf3bd8dceb9a92e6aa1957") }
Following is the query to display all documents from a collection with the help of find() method −
> db.prependDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5ccf3bcedceb9a92e6aa1955"), "StudentFirstName" : "John" } { "_id" : ObjectId("5ccf3bd3dceb9a92e6aa1956"), "StudentFirstName" : "Chris" } { "_id" : ObjectId("5ccf3bd8dceb9a92e6aa1957"), "StudentFirstName" : "Robert" }
Here is the query to prepend string to entire column in MongoDB −
> db.prependDemo.aggregate([{ ... $project: { ... "StudentFirstName": { ... $concat: ["Mr.", "$StudentFirstName"] ... } ... } ... }]);
This will produce the following output −
{ "_id" : ObjectId("5ccf3bcedceb9a92e6aa1955"), "StudentFirstName" : "Mr.John" } { "_id" : ObjectId("5ccf3bd3dceb9a92e6aa1956"), "StudentFirstName" : "Mr.Chris" } { "_id" : ObjectId("5ccf3bd8dceb9a92e6aa1957"), "StudentFirstName" : "Mr.Robert" }