How to calculate and update average value in mongodb?

Viewed 222

I want to update avg field every time when updating star.

{
  _id : "001",
  star: {
    avg: 2.6
    count: 3,
    _1: 1,
    _2: 0,
    _3: 1,
    _4: 1,
    _5: 0,
  }
}

How can I update avg field ?

// `avg` should update to number 2 where { count: 2, _1: 1, _3: 1 }
db.Collection.updateOne({_id:"001"},{ $inc:{ "star._4": -1 , "star.count": -1 }})

// `avg` should update to number 3.5 where { count: 2, _4: 1, _3: 1 }
db.Collection.updateOne({_id:"001"},{ $inc:{ "star._1": -1 , "star._4": 1 }})

0 Answers
Related