使用MongoDB的MapReduce Java驱动程序错误的BSONElement断言类型错误
我是MongoDB和MapReduce的新手。 我需要在我的数据库中的集合上做一些MapReduce。 MAP
和REDUCE_MAX
函数可以工作,因为我能够在Mongo交互式shell(v.1.8.2)中完成我的需求。 但是,使用Mongo Java驱动程序(v.2.6.3)尝试执行相同的操作时出错
我的MAP
和REDUCE_MAX
函数如下所示:
String MAP = "function(){" + "if(this.type != \"checkin\"){return;}" + "if(!this.venue && !this.venue.id){return;}" + "emit({userId:this.userId, venueId:this.venue.id}, {count:1});" + "};"; String REDUCE_MAX = "function(key, values){" + "var res = {count:0};" + "values.forEach(function(value){result.count += value.count;});" + "return res;" + "};";
这是我正在执行的命令:
MapReduceOutput sum = collection .mapReduce(MAP, REDUCE_MAX, null, null);
这是我得到的错误:
com.mongodb.CommandResult$CommandFailure: command failed [command failed [mapreduce] { "assertion" : "wrong type for BSONElement (replace) 10 != 2" , "assertionCode" : 13111 , "errmsg" : "db assertion failure" , "ok" : 0.0}
我不知道哪个BSONElement的类型错误。 我已经用google搜索了assertionCode: 13111
。 我还检查了MongoDB日志,但没有找到任何线索。
有没有人有想法,我可能会错过/做错什么? 如果你们需要更多细节,请告诉我们。
今天我偶然发现了我的错误并计划在这里分享解决方案,以防有人遇到类似的问题。
mapReduce
方法的调用导致了这个问题:
MapReduceOutput sum = collection .mapReduce(MAP, REDUCE_MAX, null, null);
看看这个方法的Javadoc:
/** * performs a map reduce operation * Runs the command in REPLACE output mode (saves to named collection) * * @param map * map function in javascript code * @param outputTarget * optional - leave null if want to use temp collection * @param reduce * reduce function in javascript code * @param query * to match * @return * @throws MongoException * @dochub mapreduce */
它声明该命令是使用REPLACE
作为输出模式执行的,如果需要临时集合,则outputTarget
应为null
。
不幸的是,在mapReduce
方法中使用的构造函数MapReduceCommand
只允许outputTarget
为null,如果OutputType
设置为INLINE
(根据MapReduceCommand.getOutputTarget()
的Javadoc)。
所以我所要做的就是将第三个参数从null
更改为某个String
,如下所示:
MapReduceOutput sum = collection .mapReduce(MAP, REDUCE_MAX, "tmp", null);
这就像我在尝试弄清楚它为什么不起作用时没有玩过的唯一参数。 我希望有人可能会觉得这很有帮助。
您可能还想尝试:
MapReduceOutput sum = collection.mapReduce(MAP, REDUCE_MAX, null, OutputType.INLINE, null);
如果你想要一个内联集合而不给它一个名字