I wrote the following aggregation pipeline that returns the most liked items in my users collection
db.users.aggregate([
{$unwind: "$favoriteItems"},
{$group: {
_id: "$favoriteItems" ,
likes: { $sum: 1 }
}},
{$sort: { likes: -1 }}
])
Here is a prototype document from my users collection:
{
"_id": "5a6df13552f42a34dcca9aa6",
"username": "user1",
"favoriteItems": [
{
"_id": "5a0c6b2dfd3eb67969316d6d",
"name": "item1"
},
{
"_id": "5a0c680afd3eb67969316d0b",
"name": "item2"
}
]
}
This is my attempt at doing the same in 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());
}
}
This is not yielding any output. What am i missing here?
EDIT LikedItem.java
public class LikedItem {
private Item id;
private float value;
// empty and full constructor + getters and setters
}
EDIT 2 Item class
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
}
Document result = mongoTemplate.aggregate(aggregation, "users", LikedItem.class).getRawResults();to view what you get back from mongo