小编典典

Spring-mongodb-聚合-需要'cursor'选项

spring-boot

执行以下聚合管道:

public void getMostLikedItems () {
        UnwindOperation unwind = Aggregation.unwind("favoriteItems");
        GroupOperation group = Aggregation.group("favoriteItems").count().as("likes");
        SortOperation sort = Aggregation.sort(Sort.Direction.DESC, "likes");

        Aggregation aggregation = newAggregation(unwind, group, sort);
        DBObject result = mongoTemplate.aggregate(aggregation, "users", LikedItem.class).getRawResults();
}

引发以下异常:

com.mongodb.MongoCommandException: Command failed with error 9: 'The 'cursor' option is required, except for aggregate with the explain argument' on server localhost:27017. The full response is { "ok" : 0.0, "errmsg" : "The 'cursor' option is required, except for aggregate with the explain argument", "code" : 9, "codeName" : "FailedToParse" }

我不明白这里的光标选项是什么意思。该选项应在哪里配置?

编辑 这是一个示例用户文档

{
  "_id": "5a6df13552f42a34dcca9aa6",
  "username": "user1",
  "password": "$2a$10$p0OXq5PPa41j1e4iPcGZHuWjoKJ983sieS/ovFI.cVX5Whwj21WYi",
  "favoriteItems": [
    {
      "_id": "5a0c6b2dfd3eb67969316d6d",
      "name": "item1",
      "city": "Rabat"
    },
    {
      "_id": "5a0c680afd3eb67969316d0b",
      "name": "item2",
      "city": "Rabat"
    }
  ]
}

阅读 1006

收藏
2020-05-30

共1个答案

小编典典

从文档。

MongoDB
3.4不建议使用不带游标选项的聚合命令,除非管道包括解释选项。使用聚合命令以内联方式返回聚合结果时,请使用默认批处理大小游标:{}指定游标选项,或在游标选项游标:{batchSize:}中指定批处理大小。

你可以通过batchSizeAggregationOptions在spring蒙戈2.x版

Aggregation aggregation = newAggregation(unwind, group).withOptions(newAggregationOptions().cursorBatchSize(100).build());

使用默认批次大小

Aggregation aggregation = newAggregation(unwind, group).withOptions(newAggregationOptions().cursor(new Document()).build());
2020-05-30