首页 > 解决方案 > 使用 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
}

如果有人可以提供帮助,将不胜感激

标签: mongodbsumaverageaggregation

解决方案


$sum接受一个数组,这意味着您只需调整您当前拥有的内容:

db.movies.aggregate([
    {
        $addFields: {
            totalScore: {
                $sum: ["$meter", "$userMeter", "$metacritic"]
            }
        }
    }
])

推荐阅读