【发布时间】: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