D
D
Devero972021-07-02 10:34:01
MongoDB
Devero97, 2021-07-02 10:34:01

How to get the average rating from an array with objects. Mongoose?

I have an array of comments, each comment has its own array with objects. Each object has two keys

[
{
name: 'Имя'
rating: 4
},
{
name: 'Имя'
rating: 4
},
{
name: 'Имя'
rating: 4
}
]

I want to get the average of all comments by counting each rating.
That is, in each comment, get the average and only then get the average from all comments and put it in another variable. I use mongoose but there is no information about it in the docs. Can this be done at all?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Chernyshev, 2021-07-07
@IvanBlacky

You can, for example, use MongoDB's Aggregation Pipeline tool . It is difficult to offer a specific solution without having a description of the entire model, but as an approximate option, I can offer the following. First, unwind your array, then make a group by comment with the introduction of an additional field, which will be the average value of the rating field for the elements of this array, and then another group, already for all comments, where one more field will be introduced with the average value of that field , which was introduced earlier. The link I left above has a detailed description of the operations that I proposed, and mongoose supports the aggregation pipeline.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question