สำหรับการแยกสตริงใน MongoDB ให้ใช้ mapReduce() เนื่องจาก Aggregation Pipeline เดิมไม่มีตัวดำเนินการ $split (เพิ่มเข้ามาในรุ่นใหม่)
สร้างคอลเลกชันพร้อมเอกสาร:
> db.splitString.insertOne({"StudentName":"John Smith"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e0849d925ddae1f53b62206") }
แสดงเอกสารทั้งหมด:
> db.splitString.find().pretty();
ผลลัพธ์:
คำสั่ง mapReduce: ฟังก์ชัน map ใช้ JavaScript split() แยกชื่อด้วย whitespace, reverse() แล้ว取 [0] (คำสุดท้าย), toUpperCase(), แล้ว emit ใหม่:
> db.splitString.mapReduce( ... function() { ... var StudentLastName = this.StudentName.split(/\s/).reverse()[0].toUpperCase(); ... emit({ "StudentLastName": StudentLastName, "FirstObjectId": this._id }, this); ... }, ... function(){}, ... { "out": { "inline": 1 } } ... );ผลลัพธ์ - ได้นามสกุล "SMITH" พร้อม ObjectId ต้นทาง: