mongodb Mongo按多个道具汇总

tct7dpnv  于 2022-11-03  发布在  Go
关注(0)|答案(2)|浏览(184)

我需要从Mongodb中的用户集合生成统计数据

用户模式

{
  _id: ObjectId,
  name: string,
  city: string,
  gender: enunm["Male", "Female"],
}

统计模式

[
  {
    city: string,
    Male: number, (number of males in that $city)
    Female: number, (number of females in that $city)
  }
]

应使用什么聚合管道?

我试过这样的方法:

db.testCollection.aggregate([
  { $group: { _id: "$status", totalQuantity: { $count: "$stats" } } },
]);
plicqrtu

plicqrtu1#

您希望在分组时使用$cond对性别值进行有条件求和,如下所示:

db.collection.aggregate([
  {
    $group: {
      _id: "$city",
      Male: {
        $sum: {
          $cond: [
            {
              $eq: [
                "$gender",
                "Male"
              ]
            },
            1,
            0
          ]
        }
      },
      Female: {
        $sum: {
          $cond: [
            {
              $eq: [
                "$gender",
                "Female"
              ]
            },
            1,
            0
          ]
        }
      }
    }
  },
  {
    $project: {
      Female: 1,
      Male: 1,
      city: "$_id",
      _id: 0
    }
  }
])

Mongo Playground

c86crjj0

c86crjj02#

另一种方法是:

db.collection.aggregate([
  { $unset: ["name"] },
  {
    $group: {
      _id: { city: "$city", gender: "$gender" },
      total: { $count: {} },
    },
  },
  {
    $group: {
      _id: "$_id.city",
      genders: { $push: { k: "$_id.gender", v: "$total" } },
    },
  },
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [{ city: "$_id" }, { $arrayToObject: "$genders" }],
      },
    },
  },
]);

相关问题