Mongoose: Sum of all points queried by a particular user

Viewed 94

I have a collection in Mongoose called Points where I have a history of all points of a user

This is the point schema

const PointSchema = mongoose.Schema({
   user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
      required: true,
   },
   reason: {
      type: String,
      required: true,
   },
   points: {
      type: Number,
      required: true,
   },
   time: {
      type: Date,
      default: Date.now,
   },
});

I want a JSON output like this

{
   "points": 30,
   "history": [
      { Point object },
      { Point object },
      { Point object },
   ]
}

How can I get the sum of all the points queried by a particular user, and get the output as above if I have the particular user's id?

1 Answers

You could do a simple aggregation where you first $match the user-id, then $sum all the points and finally push each document to the history array:

db.collection.aggregate([
  {
    "$match": {
      user: "<user-id-to-match>"
    }
  },
  {
    "$group": {
      "_id": "$user",
      "points": {
        $sum: "$points"
      },
      history: {
        "$push": "$$ROOT"
      }
    }
  },
  {
    $project: {
      _id: 0
    }
  }
])

Here's an example I've created on mongoplayground: https://mongoplayground.net/p/Q_TtcI_dkZu

Related