MongoDB Java聚合函数的游标错误

时间:2018-10-14 16:13:46

标签: mongodb mongodb-java

  

我正试图从MongoDB中获取数据,以获取最受欢迎的5种产品。

     
    

但是我遇到了错误。 (MongoDB版本3.2.21)

         

com.mongodb.MongoCommandException:命令失败,错误9:“'cursor'选项是必需的,但带有本地解释参数的聚合”在服务器localhost:27017上。完整的响应为{“ ok”:0.0,“ errmsg”:“'cursor'选项是必需的,除了带有explain参数的聚合”,“ code”:9,“ codeName”:“ FailedToParse”}

  
DBObject groupFields = groupFields = new BasicDBObject("_id", 0);
groupFields.put("_id", "$productId");               
groupFields.put("avgRating", new BasicDBObject("$avg", "$productRvR")); 
groupFields.put("productModelName", new BasicDBObject("$push", "$productMN"));
DBObject group = new BasicDBObject("$group", groupFields);

DBObject projectFields = new BasicDBObject("_id", 0);
projectFields.put("productId", "$_id");
projectFields.put("avgRating", "$avgRating");
projectFields.put("productModelName", "$productModelName");
DBObject project = new BasicDBObject("$project", projectFields);

DBObject sort = new BasicDBObject();
sort.put("avgRating",-1);
DBObject orderby=new BasicDBObject("$sort",sort);
DBObject limit=new BasicDBObject("$limit",5);

AggregationOutput aggregate userReviews.aggregate(group,project,orderby,limit);

LinkedHashMap<String, String> mostLikedProductsMap = new LinkedHashMap<String, String>();

for (DBObject queryResult : aggregate.results()) {
    BasicDBObject obj = (BasicDBObject) queryResult;
    BasicDBList productModelName = (BasicDBList) obj.get("productModelName");

    mostLikedProductsMap.put((String)productModelName.get(0),obj.getString("avgRating"));

                }

return mostLikedProductsMap;

0 个答案:

没有答案