Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Tách chuỗi trong MongoDB Aggregation với mapReduce

Để tách chuỗi trong aggregation, có thể sử dụng mapReduce() (cách truyền thống) hoặc từ MongoDB 4.0+ dùng $split trong aggregation pipeline.

Tạo collection:

> db.splitString.insertOne({"StudentName":"John Smith"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e0849d925ddae1f53b62206") }

Hiển thị dữ liệu:

> db.splitString.find().pretty();

Sử dụng mapReduce tách họ/tên, lấy tên cuối (Smith), chuyển hoa, emit kết quả:

> db.splitString.mapReduce(
...   function() {
...     var StudentLastName = this.StudentName.split(/\s/).reverse()[0].toUpperCase();
...     emit({ "StudentLastName": StudentLastName, "FirstObjectId": this._id }, this);
...   },
...   function(){},
...   { "out": { "inline": 1 } }
...);

Kết quả trả về tên họ in hoa "SMITH":

Lưu ý hiện đại: Từ MongoDB 4.0+, nên dùng aggregation với $split, $arrayElemAt, $toUpper thay vì mapReduce.