嗨,我正在尝试使用添加字段来做一条聚合语句,以从其他字段中获取值并计算平均得分。我想从中获得平均分数的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
}
如果有人可以帮助您,请
答案 0 :(得分:0)
$sum接受一个数组,这意味着您只需要调整当前的内容即可:
db.movies.aggregate([
{
$addFields: {
totalScore: {
$sum: ["$meter", "$userMeter", "$metacritic"]
}
}
}
])