You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB聚合需求:统计记录数并与另一集合字段相乘

我来帮你搞定这个MongoDB的统计与运算需求~先结合你给出的Invoice数据,一步步给你实现方案:

步骤1:统计Invoice集合的记录数

首先我们需要精确统计Invoice里的总记录数,用countDocuments()方法就可以实现(如果只是估算记录数,也可以用estimatedDocumentCount(),速度更快但精度稍低):

// 统计Invoice集合的总记录数
const invoiceTotalCount = db.Invoice.countDocuments({});
print(`Invoice集合总记录数:${invoiceTotalCount}`);

针对你提供的3条有效插入数据,执行后会返回3。

步骤2:获取另一个集合的目标字段值

假设你要关联的是和SupplierType对应的集合(比如叫Supplier),这个集合里有需要用来相乘的字段(比如Multiplier)。先给你补个示例的Supplier数据插入(如果你的集合已经存在,这步可以跳过):

// 插入示例Supplier数据,包含SupplierType和对应的乘数字段
db.Supplier.insert({"SupplierType": "Meat", "Multiplier": 1.2});
db.Supplier.insert({"SupplierType": "Veg", "Multiplier": 0.9});

然后我们可以通过findOne()获取指定文档的目标字段值,比如取SupplierType为Meat的乘数:

// 获取Supplier集合中指定类型的Multiplier值
const targetMultiplier = db.Supplier.findOne({"SupplierType": "Meat"}).Multiplier;
print(`要用到的乘数:${targetMultiplier}`);
步骤3:执行相乘运算

拿到两个数值后,直接做乘法运算即可:

// 计算最终结果
const finalResult = invoiceTotalCount * targetMultiplier;
print(`统计数与字段值相乘的结果:${finalResult}`);

代入示例数据的话,就是3 * 1.2 = 3.6,执行后会输出这个结果。

进阶:按分组关联计算(如果需要)

如果你想按SupplierType分组统计Invoice数量,再分别和对应Supplier的乘数相乘,可以用MongoDB的聚合管道来实现,这样能一次性完成统计、关联和计算:

db.Invoice.aggregate([
  // 按SupplierType分组,统计每组的Invoice数量
  {
    $group: {
      _id: "$SupplierType",
      invoiceGroupCount: {$sum: 1}
    }
  },
  // 关联Supplier集合,获取对应类型的乘数
  {
    $lookup: {
      from: "Supplier",
      localField: "_id",
      foreignField: "SupplierType",
      as: "supplierInfo"
    }
  },
  // 展开关联的Supplier数据
  {
    $unwind: "$supplierInfo"
  },
  // 计算每组的相乘结果并格式化输出
  {
    $project: {
      供应商类型: "$_id",
      该类型发票数量: "$invoiceGroupCount",
      乘数: "$supplierInfo.Multiplier",
      最终结果: {$multiply: ["$invoiceGroupCount", "$supplierInfo.Multiplier"]}
    }
  }
])

执行这个聚合后,会返回每个SupplierType对应的统计和计算结果,比如Meat类型是2 * 1.2 = 2.4,Veg类型是1 * 0.9 = 0.9。

内容的提问来源于stack exchange,提问作者Jamie Lewis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:49:40