我正在使用 MongoDB v1.4 和 mongodb-csharp driver我尝试对具有超过 10000 个键的数据存储进行分组,所以我收到此错误:
断言:group() 不能处理超过 10000 个唯一键
像这样使用 c# 代码:
Document query = new Document().Append("group",
new Document()
.Append("key", new Document().Append("myfieldname", true).Append("length", true))
.Append("$reduce",
new CodeWScope(
"function(obj,prev) { prev.count++; }"))
.Append("initial", new Document().Append("count", 0))
.Append("ns", "myitems"));
我读到我应该使用 map/reduce,但我不知道如何使用。有人可以解释一下如何使用 map/reduce 吗?
或者有没有其他方法可以绕过这个限制?
谢谢。
编辑:我忘记了我的 key 集合中有 2 列,补充说。
最佳答案
感谢达林·迪米特洛夫。
此外,如果有人对此感兴趣,我将按两个字段分组发布我的解决方案:
string mapFunction = @"
function(){
emit({
fieldname:this.fieldname,
length:this.length
}, 1)
}";
string reduceFunction =
@"function(k,vals)
{
var sum = 0;
for(var i in vals) {
sum += vals[i];
}
return sum;
}";
IMongoCollection mrCol = db["table"];
using (MapReduceBuilder mrb = mrCol.MapReduceBuilder().Map(mapFunction).Reduce(reduceFunction))
{
using (MapReduce mr = mrb.Execute())
{
foreach (Document doc in mr.Documents)
{
// do something
int groupCount = Convert.ToInt32(doc["value"]);
string fieldName = ((Document)doc["_id"])["fieldname"].ToString();
}
}
}
关于mongodb - 如何使用 map/reduce 处理 10000 多个唯一键以在 MongoDB 中进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2599665/