有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用MongoDB Java驱动程序的MapReduce因BSOneElement断言类型错误而失败

我对MongoDB和MapReduce很陌生。我需要在数据库中的集合上执行一些MapReduce。{}和{}函数可以工作,因为我能够在Mongo交互式shell(v.1.8.2)中完成我的需求。但是,我在尝试使用MongoJava驱动程序(2.6.3版)执行相同的操作时出错

我的MAPREDUCE_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的类型是错误的。我已经在谷歌上搜索过了。我也检查了MongoDB日志,但没有发现任何线索

有人知道我可能错过了什么/做错了什么吗?如果你们需要更多的细节,请告诉我


共 (2) 个答案

  1. # 1 楼答案

    你可能还想试试:

    MapReduceOutput sum = collection.mapReduce(MAP, REDUCE_MAX, null, 
                      OutputType.INLINE, null);
    

    如果你想拥有一个内联集合而不给它命名

  2. # 2 楼答案

    今天,我偶然发现了我的错误,想在这里分享解决方案,以防有人遇到类似的问题

    调用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只允许outputTargetOutputType设置为INLINE时为空(根据MapReduceCommand.getOutputTarget()的Javadoc)

    所以我要做的就是把第三个参数从null改成String,如下所示:

    MapReduceOutput sum = collection
                    .mapReduce(MAP, REDUCE_MAX, "tmp", null);
    

    这是我在试图找出它为什么不起作用时唯一没有使用的参数。我希望有人会觉得这很有帮助