Оператор агрегации для расчета среднего с аддфилдом - PullRequest
0 голосов
/ 15 марта 2020

Привет. Я пытаюсь выполнить агрегирование с добавлением полей, чтобы получить значения из других полей и вычислить средний балл. 3 поля, из которых я хочу получить средний балл: tomato.meter, tomato.userMeter и metacriti c

Я попытался сделать это утверждение, чтобы получить общий балл и затем получить среднее значение totalScore чтобы получить желаемое значение. Однако я не могу заставить работать оператор сумм

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

Вот пример mov ie из базы данных со всеми полями

    "_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
}

Если кто-нибудь может помочь, это будет оценено

1 Ответ

0 голосов
/ 15 марта 2020

$ sum принимает массив, означающий, что вам просто нужно настроить то, что у вас есть:

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