mongodb - 使用 addfield 计算平均值的聚合语句
问题描述
您好我正在尝试使用添加字段来执行聚合语句以从其他字段中获取值并计算平均分数。我想获得平均分的 3 个字段是tomato.meter、tomato.userMeter 和 metacritic
我试着做这个陈述,这样我就可以得到总分,然后取 totalScore 的平均值来得到想要的值。但是我无法使 sum 语句起作用
db.movies.aggregate([{$addFields:{totalScore{$sum: {"$meter"},{"$userMeter"},{"$metacritic"}}}}])
这是数据库中包含所有字段的示例电影
"_id" : ObjectId("5e691e99fceb31c7d6cc3150"),
"title" : "Star Wars: Episode II - Attack of the Clones",
"year" : 2002,
"rated" : "PG",
"runtime" : 142,
"countries" : [
"USA"
],
"genres" : [
"Action",
"Adventure",
"Fantasy"
],
"director" : "George Lucas",
"writers" : [
"George Lucas",
"Jonathan Hales",
"George Lucas"
],
"actors" : [
"Ewan McGregor",
"Natalie Portman",
"Hayden Christensen",
"Christopher Lee"
],
"plot" : "Ten years after initially meeting, Anakin Skywalker shares a forbidden romance with Padmé, while Obi-Wan investigates an assassination attempt on the Senator and discovers a secret clone army crafted for the Jedi.",
"poster" : "http://ia.media-imdb.com/images/M/MV5BMTY5MjI5NTIwNl5BMl5BanBnXkFtZTYwMTM1Njg2._V1_SX300.jpg",
"imdb" : {
"id" : "tt0121765",
"rating" : 6.7,
"votes" : 425728
},
"tomato" : {
"meter" : 66,
"image" : "fresh",
"rating" : 6.7,
"reviews" : 242,
"fresh" : 159,
"consensus" : "Star Wars Episode II: Attack of the Clones benefits from an increased emphasis on thrilling action, although they're once again undercut by ponderous plot points and underdeveloped characters.",
"userMeter" : 58,
"userRating" : 3.3,
"userReviews" : 844634
},
"metacritic" : 54,
"awards" : {
"wins" : 13,
"nominations" : 47,
"text" : "Nominated for 1 Oscar. Another 13 wins & 47 nominations."
},
"type" : "movie",
"myRating" : false
}
如果有人可以提供帮助,将不胜感激
解决方案
$sum接受一个数组,这意味着您只需调整您当前拥有的内容:
db.movies.aggregate([
{
$addFields: {
totalScore: {
$sum: ["$meter", "$userMeter", "$metacritic"]
}
}
}
])
推荐阅读
- jquery - Jquery DataTable - 更改服务器端数据格式
- javascript - 每个用户的 Firebase 文档?
- javascript - 散景 HTML 模板格式化程序不起作用
- sapui5 - SAPUI5 Northwind 和 mockServer
- jquery - 外部 jQuery 文件不适用于 Angular 4
- git - 颜色名称的语法
- spring - 如何在 Spring 中编辑 Whitelabel 错误页面
- python-3.x - 如何使用python绘制具有不平衡数据的2个变量之间的散点图?
- javascript - 重定向和检查登录不适合我
- json - 使用 JSON 文件创建数据库