【问题标题】:MongoDB / Mongoose: Return value of aggregation (sum)MongoDB / Mongoose:聚合的返回值(总和)
【发布时间】:2022-10-13 06:12:54
【问题描述】:

我希望有人可以帮助我:我想用javascript和猫鼬写一点代码。我的目标是:人们可以使用在线公式登录活动。 他们必须指定姓氏、人数(每组)、电子邮件、时间(时段)。 我想编写一个控制结构来检查一个插槽中是否已经有特定数量的人(例如,插槽 11 时钟中最多 50 人)。 我不知道如何从聚合中返回单个值。

我的代码:

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"}
        }}
            ])
     

}

有人能帮助我吗? 抱歉英语不好。

来自德国的问候 戴夫

【问题讨论】:

标签: javascript mongodb mongoose aggregate


【解决方案1】:

https://mongoplayground.net/p/x8H83d4RO9x

输入:

[
  {
    lastname: "Beckenbauer",
    people: 11,
    email: "franz@beckenbauer.de",
    time: 1
  },
  {
    lastname: "Funkel",
    people: 22,
    email: "friedhelm@funkel.de",
    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: "karl-heinz@rummenigge.de",
    time: 3
  }
]

聚合:

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

结果:

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

假设您只有 3 个插槽。如果您需要更多,请扩展boundaries。此外,为了简化它,插槽表示为索引(如果需要,我们可以轻松切换到 Date)

你的英语还是比我的德语好;)

【讨论】:

    猜你喜欢
    • 2017-02-28
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 2016-11-16
    • 2016-05-20
    • 2021-09-16
    • 2016-02-17
    • 1970-01-01
    相关资源
    最近更新 更多