在 MongoDB 聚合期間分隔字串
為此,請使用 mapReduce()。我們首先使用文件建立一個集合 -
> db.splitString.insertOne({"StudentName":"John Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5e0849d925ddae1f53b62206") }
下面是使用 find() 方法從集合中顯示所有文件的查詢 -
> db.splitString.find().pretty();
這將產生以下輸出 -
{ "_id" : ObjectId("5e0849d925ddae1f53b62206"), "StudentName" : "John Smith" }
下面是分隔字串的查詢 -
> db.splitString.mapReduce( ... function() { ... var StudentLastName = this.StudentName.split(/\s/).reverse()[0].toUpperCase(); ... ... emit({ "StudentLastName": StudentLastName, "FirstObjectId": this._id },this); ... }, ... function(){}, ... { "out": { "inline": 1 } } ... );
這將產生以下輸出 -
{ "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 }
廣告