Dave90
Dave90

Reputation: 1

MongoDB / Mongoose: Return value of aggregation (sum)

I hope someone can help me: I want to write a little code with javascript and mongoose. My goal is: People can sign in for an event by using an online-formula. They have to specify last name, amount of people (per group), email, time (slot). I want to write a control structure that checks if there is already a specific number of people in one slot (for example max. 50 people in slot 11 clock). I don't know how to return a single value out of the aggregation.

My code:

const notesSchema = {
    lastname: String,
    people: Number,
    email: String,
    time: Number
}

const Note = mongoose.model("Note", notesSchema)

async function totalamount(){
    Note.aggregate(
        [{
        $group:
        {
            _id: null,
        total: { $sum: "$people"}
        }}
            ])
     

}

Can someone help me, please? Sorry for by bad english.

Best regards from Germany Dave

Upvotes: 0

Views: 43

Answers (1)

DraganS
DraganS

Reputation: 2699

https://mongoplayground.net/p/x8H83d4RO9x

Input:

[
  {
    lastname: "Beckenbauer",
    people: 11,
    email: "[email protected]",
    time: 1
  },
  {
    lastname: "Funkel",
    people: 22,
    email: "[email protected]",
    time: 2
  },
  {
    lastname: "Löw",
    people: 25,
    email: "joachim@löw.de",
    time: 1
  },
  {
    lastname: "Matthäus",
    people: 30,
    email: "lothar@matthäus.de",
    time: 2
  },
  {
    lastname: "Karl-Heinz Rummenigge",
    people: 38,
    email: "[email protected]",
    time: 3
  }
]

Agg:

db.collection.aggregate([
  {
    "$bucket": {
      "groupBy": "$time",
      "boundaries": [
        1,
        2,
        3
      ],
      "default": "literal",
      "output": {
        "total": {
          "$sum": "$people"
        },
        "lastname": {
          $push: "$lastname"
        }
      }
    }
  }
])

Result:

[
  {
    "_id": 1,
    "lastname": [
      "Beckenbauer",
      "Löw"
    ],
    "total": 36
  },
  {
    "_id": 2,
    "lastname": [
      "Funkel",
      "Matthäus"
    ],
    "total": 52
  },
  {
    "_id": "literal",
    "lastname": [
      "Karl-Heinz Rummenigge"
    ],
    "total": 38
  }
]

It's assumed that you have only 3 slots. If you need more, extend boundaries. Also, in order to simplify it slots are represented as indices (we can easily switch to Date if it's needed)

Your English is still better then my German ;)

Upvotes: 1

Related Questions