我正在使用MongoDB v1.4和mongodb-csharp driver,我尝试对具有超过10000个密钥的数据存储进行分组,因此我收到此错误:
assertion: group() can't handle more than 10000 unique keys
使用这样的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吗? 或者还有其他方法来解决这个限制吗? 感谢。
编辑:我忘了我的密钥集中有2列,添加了。答案 0 :(得分:3)
感谢Darin Dimitrov。
此外,如果有人对此感兴趣,我会将我的解决方案发布到两个字段:
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();
}
}
}
答案 1 :(得分:1)
尝试以下map/reduce
功能:
map = function() {
emit(this.myfieldname, 1);
}
reduce = function(k, vals) {
var sum = 0;
for(var i in vals) {
sum += vals[i];
}
return sum;
}