mongo-db聚合查询在mongo shell上工作,但在java程序中没有

时间:2013-03-13 09:02:55

标签: java mongodb

我正在开发一个项目,我的mongo db里面有一个巨大的集合。现在我必须从mongo db中获取一些非常类似SQL group by子句的详细信息。我在mongo shell上成功执行了查询:

    > db.votes.aggregate(
    ... { $group : {
    ... _id : "vote_post_id",
    ... votesPerId : { $sum : 1 }
    ... }}
    ... );
    {
"result" : [
            {
                    "_id" : "vote_post_id",
                    "votesPerId" : 27371750
            }
    ],
    "ok" : 1

    }
    >

现在,当从java程序执行查询时,我面临以下错误:

    Exception in thread "main" com.mongodb.CommandResult$CommandFailure: command 
    failed [aggregate]: { "serverUsed" : "localhost/127.0.0.1:27017" , 
    "errmsg" : "exception: aggregation result exceeds maximum document size (16MB)"
     , "code" : 16389 , "ok" : 0.0}
    at com.mongodb.CommandResult.getException(CommandResult.java:88)
    at com.mongodb.CommandResult.throwOnError(CommandResult.java:134)
    at com.mongodb.DBCollection.aggregate(DBCollection.java:1311)
    at main.Connetion.CheckConnection.GetNoOfVotesForAType(CheckConnection.java:210)
    at main.DAO.Votes.VoteDAO.findKeyWord(VoteDAO.java:109)
    at main.DAO.Votes.VoteDAO.main(VoteDAO.java:139)

我调试了我的java程序,它正在生成我在mongo shell上写的确切查询:

    { "$group" : { "_id" : "$vote_post_id" , "count" : { "$sum" : 1}}}

我已经为这个问题找到了很多答案,似乎没有人解决这个问题。

我创建聚合函数的java代码:

//创建我们的管道操作,首先使用$ match         DBObject match = new BasicDBObject(“$ match”,new BasicDBObject(“vote_type_id”,“1”));

    // build the $projection operation
    DBObject fields = new BasicDBObject("vote_post_id", 1);
    fields.put("_id", 0);
    DBObject project = new BasicDBObject("$project", fields );

    // Now the $group operation
    DBObject groupFields = new BasicDBObject( "_id", "$vote_post_id");
    groupFields.put("count", new BasicDBObject( "$sum", 1));
    DBObject group = new BasicDBObject("$group", groupFields);

    // run aggregation
    AggregationOutput output = votesCollection.aggregate( match, project, group );

    System.out.println(output.getCommandResult());

2 个答案:

答案 0 :(得分:1)

要使您的查询与shell中的查询相同,它将是:

// $group operation
DBObject groupFields = new BasicDBObject( "_id", "vote_post_id");
groupFields.put("votesPerId", new BasicDBObject( "$sum", 1));
DBObject group = new BasicDBObject("$group", groupFields);

// run aggregation
AggregationOutput output = votesCollection.aggregate( group );

System.out.println(output.getCommandResult());

答案 1 :(得分:0)

在你的shell查询中,你正在做

_id : "vote_post_id",

但是在你的Java查询中你正在做

"_id", "$vote_post_id"

区别在于美元符号。 $vote_post_id替换该字段的值作为存储区键,而vote_post_id只使用该字面值(因此只有一个存储区)。