在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
}