Answer the question
In order to leave comments, you need to log in
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
}
]
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question