Answer the question
In order to leave comments, you need to log in
How to sort by formula in MongoDB?
There is a task
There are 10k items in the database that have prices for 7 services.
When choosing two services, you need to find the most profitable according to the formula.
But here the question arises - how best to do it without crutches?
Is there a way to make a request, or is there a better way?
So far, my option is to receive all items, sort through, count and return the most profitable 100
In the database, it will not be possible to store a field with a percentage (it is calculated by a formula), because then there will be 49 such fields, because 7 services can interact with each other in both sides.
Answer the question
In order to leave comments, you need to log in
look at addFields, you can make another field where everything is calculated "according to the formula", and then like sort: { newField: -1 }
https://docs.mongodb.com/manual/reference/operator...
db.scores.aggregate( [
{
$addFields: {
totalHomework: { $sum: "$homework" } , // сумма массива
totalQuiz: { $sum: "$quiz" } // сумма массива
}
},
{
$addFields: { totalScore:
{ $add: [ "$totalHomework", "$totalQuiz", "$extraCredit" ] } } // два новых поля + одно старое
}
] )
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question