gpt4 book ai didi

java - spring mongodb - 聚合管道到 java

转载 作者:可可西里 更新时间:2023-11-01 10:13:03 24 4
gpt4 key购买 nike

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

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

这是我的用户集合中的原型(prototype)文档:

{
"_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
}

最佳答案

您使用的方法不正确。

sum 方法采用引用,您会得到类似 "likes": { "$sum": "$1"} 的内容。

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

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

关于java - spring mongodb - 聚合管道到 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48489091/

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