R
R
rshruslan2020-09-15 21:18:11
Node.js
rshruslan, 2020-09-15 21:18:11

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

1 answer(s)
H
hzzzzl, 2020-09-15
@hzzzzl

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" ] } } // два новых поля + одно старое
   }
] )

although this is of course a vague answer, it’s also not clear from the question how to count what, if average, then it’s probably easier

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question