

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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 }
- Related Questions & Answers
- Replace value with a string literal during MongoDB aggregation operation
- Get substring in MongoDB aggregate
- MongoDB aggregate query to sort
- Using $redact in MongoDB aggregate?
- MongoDB Aggregate group multiple result?
- Split a string in Java
- MongoDB query to implement aggregate function
- MongoDB query to aggregate nested array
- How to aggregate array documents in MongoDB?
- Implement MongoDB Aggregate - unwind, group and project?
- How to update after aggregate in MongoDB?
- How to use MongoDB Aggregate to sort?
- MongoDB Aggregate Second Element from Input Element?
- Implement $match and $project in MongoDB aggregate
- Split a document by its subdocuments in MongoDB
Advertisements