J
J
Jack Surfer2019-09-23 20:09:02
MongoDB
Jack Surfer, 2019-09-23 20:09:02

How to calculate sum of MongoDB fields?

Hello! The question is. How to calculate the sum of fields for each user in MongoDB?
I can't figure out how to form the correct request.
uid = user id, count - column of fields to be counted for all users with a certain uid for a certain period of time.
5d88fc28ea31d702532188.png

today = datetime.datetime.now()
            count_day = db.logs.find({'uid': a['uid']}, {'date': {"$gt": today - datetime.timedelta(1)}}).count()

this is how I count the number of records, but you need to calculate the sum of count according to the same principle

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2019-09-23
@JackSurfer

db.logs.aggregate([
  {
    $match: { uid: a['uid'] }
  },
  {
    $group: {
      _id: '$uid',
      sum: { $sum: '$count' }
    }
  }
])

I tried it myself, it works, but I didn’t bother with the date, in theory, just add a condition to $match (possibly with the $and operator, but it might work)
$match: { uid: a['uid'], date: {"$gt": today - datetime.timedelta(1)} }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question