【问题标题】:spring mongodb - aggregation pipeline into javaspring mongodb - 聚合管道到java
【发布时间】:2018-07-07 10:19:32
【问题描述】:

我编写了以下聚合管道,它返回我的用户集合中最喜欢的项目

db.users.aggregate([
  {$unwind: "$favoriteItems"},
  {$group: {
    _id: "$favoriteItems" ,
    likes: { $sum: 1 }
  }},
  {$sort: { likes: -1 }}
])

这是我的用户收藏中的一个原型文档:

{
  "_id": "5a6df13552f42a34dcca9aa6",
  "username": "user1",
  "favoriteItems": [
    {
      "_id": "5a0c6b2dfd3eb67969316d6d",
      "name": "item1"
    },
    {
      "_id": "5a0c680afd3eb67969316d0b",
      "name": "item2"
    }
  ]
}

这是我在 java 中做同样的尝试:

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

        Aggregation aggregation = newAggregation(unwind, group, sort);
        AggregationResults<LikedItem > result = mongoTemplate.aggregate(aggregation, "users", LikedItem .class);
        for (LikedItem s: result) {
            System.out.println(s.getId() + ": " + s.getValue());
        }
    }

这不会产生任何输出。我在这里错过了什么?

编辑 LikedItem.java

public class LikedItem {

    private Item id;
    private float value;
    // empty and full constructor + getters and setters

}

编辑 2 物品类别

public class Item{
    @Id
    private String id;
    private String name;
    private String city;
    @GeoSpatialIndexed(type= GeoSpatialIndexType.GEO_2DSPHERE)
    private GeoJsonPoint location;

    public Shop() { super(); }
    // full constructor + getters and setters
}

【问题讨论】:

  • 您检查过日志吗?触发了什么查询?
  • @Saravana 我在 IDE 控制台和 mongod.exe 日志中什么都看不到。还有其他地方我应该检查吗?
  • 很可能你得到了一些输出,但它没有被映射。您可以将 LikedItem 添加到帖子中吗?试试Document result = mongoTemplate.aggregate(aggregation, "users", LikedItem.class).getRawResults(); 看看你从 mongo 得到了什么
  • @Veeram,我编辑了我的帖子以包含 LikedItem 类。
  • 你试过我的建议了吗?还请包括项目类别。

标签: java spring mongodb spring-boot aggregation-framework


【解决方案1】:

您使用的方法不正确。

sum 方法被引用,你会得到类似"likes" : { "$sum" : "$1" } 的东西。

改用count方法输出"likes" : { "$sum" : 1 }

GroupOperation group = Aggregation.group("favoriteItems").count().as("likes");

【讨论】:

  • 感谢指点函数错误。现在我遇到了一个例外: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" }
  • 另外,我的休息控制器返回错误描述,其中包括Command = { "aggregate" : "users" , "pipeline" : [ { "$unwind" : "$preferredShops"} , { "$group" : { "_id" : "$preferredShops" , "likes" : { "$sum" : 1}}} , { "$sort" : { "likes" : -1}}]}; nested exception is com.mongodb.MongoCommandException:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-24
  • 2020-09-20
  • 2021-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多