For this, use mapReduce(). Let us first create a collection with documents −
> db.splitString.insertOne({"StudentName":"John Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5e0849d925ddae1f53b62206") }
Following is the query to display all documents from a collection with the help of find() method −
> db.splitString.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e0849d925ddae1f53b62206"), "StudentName" : "John Smith" }
Here is the query to split a string −
> db.splitString.mapReduce( ... function() { ... var StudentLastName = this.StudentName.split(/\s/).reverse()[0].toUpperCase(); ... ... emit({ "StudentLastName": StudentLastName, "FirstObjectId": this._id },this); ... }, ... function(){}, ... { "out": { "inline": 1 } } ... );
This will produce the following output −
{ "results" : [ { "_id" : { "StudentLastName" : "SMITH", "FirstObjectId" : ObjectId("5e0849d925ddae1f53b62206") }, "value" : { "_id" : ObjectId("5e0849d925ddae1f53b62206"), "StudentName" : "John Smith" } } ], "timeMillis" : 32, "counts" : { "input" : 1, "emit" : 1, "reduce" : 0, "output" : 1 }, "ok" : 1 }