이를 위해 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
}