- 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
Split a string during MongoDB aggregate
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 }
Advertisements