如何统计使用 MongoDB 的客户总数?

问题描述 投票:0回答:2

这是 JSON 的示例。我想通过唯一的“email_address”来计算客户总数,并通过等于“S”的“transactions_status”进行过滤。

预期输出:

    {
_id: null, 
count: total amount of customers with an unique email address and filtered by status  equal S 
}

mongodb mongodb-query aggregation-framework
2个回答
0
投票

您可以尝试这个聚合管道:

  1. 按“transactions_status”等于“S”进行过滤。
  2. 将不同的电子邮件分组。
  3. 用电子邮件的大小投影计数字段。
db.collection.aggregate([
  {
    $match: {
      "transaction_info.transaction_status": "S"
    }
  },
  {
    $group: {
      _id: null,
      emails: {
        $addToSet: "$payer_info.email_address"
      }
    }
  },
  {
    $project: {
      count: {
        $size: "$emails"
      }
    }
  }
]);

0
投票

就我而言,我也试图计算客户数量,所以我必须使用订单集合来执行此操作,因为订单集合具有客户字段,我可以使用该字段来获取总客户,这是我的聚合

    [
  {
    $match: {
      $expr: {
        $eq: [
          "$shop",
          {
            $toObjectId:
              "653a5a695c5ace2932dd3765",
          },
        ],
      },
    },
  },
  {
    $match: {
      $and: [
        {
          orderStatus: {
            $ne: "deleted",
          },
        },
      ],
    },
  },
  {
    $group: {
      _id: null,
      uniqueCustomers: {
        $addToSet: "$customer",
      },
    },
  },
  {
    $project: {
      _id: "customers count",
      customers: {
        $size: "$uniqueCustomers",
      },
    },
  },
]
© www.soinside.com 2019 - 2024. All rights reserved.