0

I have document:

{
        "_id" : ObjectId("592be26fd600eb5941385396"),
        "isbn" : "978-2-1234-5680-3",
        "voices" : {
                "1" : 10,
                "2" : 25,
                "3" : 40,
                "4" : 70,
                "5" : 100
        },
        "total" : 245,
        "avg" : 3.92
}

And when I add next user voice e.g.:

db.books.update({isbn: '978-2-1234-5680-3'}, {$inc: {'voices.2': 1, 'total': 1}})

I want to calculate avg field. Can I do this in one command? For example ($set is "pseudo-code"):

db.books.update({isbn: '978-2-1234-5680-3'}, {$set: {avg: ((voices.1 * 1 +
voices.2 * 2 + voices.3 * 3 + voices.4 * 4 + voices.5 * 5) / total)}}

Od maybe I can increment one voice field and calculate avg in one command?

Nolias
  • 101
  • 1
  • 10
  • 1
    You cannot do this in one command. The linked question basically goes on to summarize this talks about different methods to update the documents. In your case I would recommend that your application logic reading the data deals with the "average" calculation rather than trying to store the value in the document itself. By all means keep updating the properties from which the average is created though. – Neil Lunn May 29 '17 at 10:56
  • I think that store the "average" calculation is better option than doing calculation for each request to page. But thanks for the answer. – Nolias May 29 '17 at 11:00

0 Answers0