在 MongoDB 3.4 中使用$split 运算符将字符串拆分为子字符串数组的最佳方法是here 提到的,因为我们需要$unwind 数组在管道中向下,我们需要使用$facet 运算符在子管道中执行此操作以获得最大效率。
db.collection.aggregate([
{ "$facet": {
"results": [
{ "$project": {
"values": { "$split": [ "$foo", " " ] }
}},
{ "$unwind": "$values" },
{ "$group": {
"_id": "$values",
"count": { "$sum": 1 }
}}
]
}}
])
产生:
{
"results" : [
{
"_id" : "boo",
"count" : 2
},
{
"_id" : "baz",
"count" : 3
},
{
"_id" : "bar",
"count" : 2
}
]
}
从 MongoDB 3.2 开始,唯一的方法是使用mapReduce。
var reduceFunction = function(key, value) {
var results = {};
for ( var items of Array.concat(value)) {
for (var item of items) {
results[item] = results[item] ? results[item] + 1 : 1;
}
};
return results;
}
db.collection.mapReduce(
function() { emit(null, this.foo.split(" ")); },
reduceFunction,
{ "out": { "inline": 1 } }
)
返回:
{
"results" : [
{
"_id" : null,
"value" : {
"bar" : 2,
"baz" : 3,
"boo" : 2
}
}
],
"timeMillis" : 30,
"counts" : {
"input" : 3,
"emit" : 3,
"reduce" : 1,
"output" : 1
},
"ok" : 1
}
如果您的 MongoDB 版本不支持 for...of 语句,您应该考虑在 reduce 函数中使用 .forEach() 方法。