[英]MongoDB average of a field for DBRef Rating
I have a Document named Rating
to which other documents Video
& User
are attached.我有一个名为
Rating
的文档,其中附加了其他文档Video
& User
。
I am trying to get an avg
rating for a supplied video id.我正在尝试获得提供的视频 ID 的
avg
评级。
My Documents definitions are as follows我的文档定义如下
@Document(value = "rating")
@NoArgsConstructor
public class Rating extends Auditable<String> {
@Getter
@Setter
@DBRef
private Video video;
@Getter
@Setter
@DBRef
private User user;
@Getter
@Setter
private int rating;
}
@Document(collection = "videos")
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Video extends Auditable<String> {
//Field omitted
}
@Document(collection = "users")
@NoArgsConstructor
public class User extends Auditable<String> {
@Getter
@Setter
private String username;
}
@NoArgsConstructor
@AllArgsConstructor
public class RatingResponse {
@Getter
@Setter
private String videoId;
@Getter
@Setter
private Integer rating;
}
My Rating Code block looks like this我的评级代码块看起来像这样
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(Criteria.where("video.$id").is(video.getId())),
Aggregation.group(Fields.fields("id"))
.avg("rating").as("rating")
);
AggregationResults<RatingResponse> results = mongoTemplate.aggregate(aggregation, Rating.class, RatingResponse.class);
RatingResponse uniqueMappedResult = results.getUniqueMappedResult();
When I execute this in the test, I get following JSON representation:当我在测试中执行此操作时,我得到以下 JSON 表示:
{ "aggregate" : "__collection__", "pipeline" : [{ "$match" : { "video.$id" : "5dbe5ce141bb7d2e137eee0b" } }, { "$group" : { "_id" : "$id", "rating" : { "$avg" : "$rating" } } }] }
I am executing these commands from spring boot framework, if there exists a better option, please kindly let me know.我正在从 spring 引导框架执行这些命令,如果有更好的选择,请告诉我。
I don't know if this is the right way to query, please help me solve this query.我不知道这是否是正确的查询方式,请帮我解决这个查询。 Thank you.
谢谢你。
Edited Added Image for reference编辑添加图片供参考
Video documents are stored as ObjectId("5dbe5ce141bb7d2e137eee0b")
, while you are searching as String
( "video.$id": "5dbe5ce141bb7d2e137eee0b"
)视频文档存储为
ObjectId("5dbe5ce141bb7d2e137eee0b")
,而您搜索为String
( "video.$id": "5dbe5ce141bb7d2e137eee0b"
)
{
"_id": ObjectId("5a934e000102030405000002"),
"video": {
"$ref": "video",
"$id": ObjectId("5dbe5ce141bb7d2e137eee0b")
},
user: {},
rating: 100
},
{
"_id": ObjectId("5a934e000102030405000004"),
"video": {
"$ref": "video",
"$id": ObjectId("5dbe5ce141bb7d2e137eee0b")
},
user: {},
rating: 40
}
db.rating.aggregate([
{
"$match": {
"video.$id": {
"$oid": "5dbe5ce141bb7d2e137eee0b"
}
}
},
{
"$group": {
"_id": "$id",
"rating": {
"$avg": "$rating"
}
}
}
])
[
{
"_id": null,
"rating": 70
}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.