我正在做一个项目,其中我的 mongo 数据库中有大量集合。现在我必须从 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());