gpt4 book ai didi

java - mongo-db 聚合查询在 mongo shell 上工作,但在 java 程序中不起作用

转载 作者:行者123 更新时间:2023-12-01 14:46:40 25 4
gpt4 key购买 nike

我正在开发一个项目,其中我的 mongo 数据库中有一个巨大的集合。现在我必须从 mongo 数据库获取一些详细信息,这些详细信息与 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());

最佳答案

要使您的查询与 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());

关于java - mongo-db 聚合查询在 mongo shell 上工作,但在 java 程序中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15380852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com