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

基于MongoDB-NodeJS驱动实现订单数据多维度求和查询

用MongoDB-NodeJS驱动实现经销商关联客户订单统计需求

完全可以实现你提出的两个统计需求,下面是结合MongoDB聚合框架和NodeJS驱动的完整实现方案,我会分步骤说明逻辑并给出可运行的代码:

前置准备

确保你已经安装了MongoDB NodeJS驱动:

npm install mongodb

需求1:统计指定经销商关联客户的全量订单产品汇总

这个需求需要先定位到目标经销商的mappedCustomers列表,再关联orders集合筛选出这些客户的订单,最后按productCode分组计算各类副本的总和。

实现代码

const { MongoClient } = require('mongodb');

// MongoDB连接字符串,根据你的环境修改
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);

async function calculateTotalCopiesByProduct(dealerId) {
  try {
    await client.connect();
    const db = client.db('your-database-name'); // 替换为你的数据库名

    // 1. 先获取目标经销商的mappedCustomers列表
    const dealer = await db.collection('masters').findOne(
      { _id: dealerId }, // 这里用经销商的唯一标识,比如_id,也可以是其他字段比如dealerCode
      { projection: { mappedCustomers: 1 } }
    );

    if (!dealer || !dealer.mappedCustomers || dealer.mappedCustomers.length === 0) {
      console.log('该经销商没有关联客户');
      return {};
    }

    // 2. 聚合orders集合,按productCode汇总各类副本
    const result = await db.collection('orders').aggregate([
      {
        $match: {
          customerId: { $in: dealer.mappedCustomers } // 筛选关联客户的订单
        }
      },
      {
        $group: {
          _id: '$productCode',
          tradeCopiesTotal: { $sum: '$tradeCopies' },
          subscriptionCopiesTotal: { $sum: '$subscriptionCopies' },
          freeCopiesTotal: { $sum: '$freeCopies' },
          institutionalCopiesTotal: { $sum: '$institutionalCopies' }
        }
      },
      {
        $project: {
          productCode: '$_id',
          tradeCopiesTotal: 1,
          subscriptionCopiesTotal: 1,
          freeCopiesTotal: 1,
          institutionalCopiesTotal: 1,
          _id: 0
        }
      }
    ]).toArray();

    // 整理成更直观的输出格式
    const formattedResult = result.reduce((acc, item) => {
      acc[item.productCode] = {
        tradeCopies: item.tradeCopiesTotal,
        subscriptionCopies: item.subscriptionCopiesTotal,
        freeCopies: item.freeCopiesTotal,
        institutionalCopies: item.institutionalCopiesTotal
      };
      return acc;
    }, {});

    return formattedResult;
  } catch (err) {
    console.error('统计出错:', err);
    throw err;
  } finally {
    await client.close();
  }
}

// 调用示例:替换为你的目标经销商ID
calculateTotalCopiesByProduct('目标经销商ID')
  .then(result => console.log('全量订单产品汇总:', result))
  .catch(err => process.exit(1));

需求2:统计指定日期(D-7日)的副本数据总和

这个需求是在需求1的基础上,增加对orderCreatedForDate的日期过滤,注意要匹配ISODate的格式。

实现代码

async function calculateCopiesByProductOnSpecifiedDate(dealerId, targetDate) {
  try {
    await client.connect();
    const db = client.db('your-database-name');

    const dealer = await db.collection('masters').findOne(
      { _id: dealerId },
      { projection: { mappedCustomers: 1 } }
    );

    if (!dealer || !dealer.mappedCustomers || dealer.mappedCustomers.length === 0) {
      console.log('该经销商没有关联客户');
      return {};
    }

    // 聚合时增加日期匹配条件
    const result = await db.collection('orders').aggregate([
      {
        $match: {
          customerId: { $in: dealer.mappedCustomers },
          orderCreatedForDate: targetDate // 传入的ISODate对象,比如ISODate("2020-01-24T18:30:00Z")
        }
      },
      {
        $group: {
          _id: '$productCode',
          tradeCopiesTotal: { $sum: '$tradeCopies' },
          subscriptionCopiesTotal: { $sum: '$subscriptionCopies' },
          freeCopiesTotal: { $sum: '$freeCopies' },
          institutionalCopiesTotal: { $sum: '$institutionalCopies' }
        }
      },
      {
        $project: {
          productCode: '$_id',
          tradeCopies: '$tradeCopiesTotal',
          subscriptionCopies: '$subscriptionCopiesTotal',
          freeCopies: '$freeCopiesTotal',
          institutionalCopies: '$institutionalCopiesTotal',
          _id: 0
        }
      }
    ]).toArray();

    // 整理成指定格式
    const formattedResult = result.reduce((acc, item) => {
      acc[item.productCode] = {
        tradeCopies: item.tradeCopies,
        subscriptionCopies: item.subscriptionCopies,
        freeCopies: item.freeCopies,
        institutionalCopies: item.institutionalCopies
      };
      return acc;
    }, {});

    return formattedResult;
  } catch (err) {
    console.error('日期统计出错:', err);
    throw err;
  } finally {
    await client.close();
  }
}

// 调用示例:替换经销商ID和目标日期
const targetDate = new Date('2020-01-24T18:30:00Z');
calculateCopiesByProductOnSpecifiedDate('目标经销商ID', targetDate)
  .then(result => console.log('指定日期订单产品汇总:', result))
  .catch(err => process.exit(1));

示例输出

假设统计结果如下,格式完全可以匹配你需要的样式:

// 全量订单汇总示例
{
  "PROD001": {
    "tradeCopies": 150,
    "subscriptionCopies": 80,
    "freeCopies": 20,
    "institutionalCopies": 45
  },
  "PROD002": {
    "tradeCopies": 90,
    "subscriptionCopies": 55,
    "freeCopies": 10,
    "institutionalCopies": 30
  }
}

// 指定日期汇总示例
{
  "PROD001": {
    "tradeCopies": 25,
    "subscriptionCopies": 10,
    "freeCopies": 5,
    "institutionalCopies": 8
  }
}

注意事项

  • 替换代码中的your-database-name为实际数据库名,目标经销商ID为你要查询的经销商唯一标识(比如_id或自定义的dealerCode)
  • 如果mappedCustomers存储的是客户的_id,确保orders集合中的customerId字段类型与之匹配(都是ObjectId或字符串)
  • 若需要处理时区问题,可以用$dateToString或$match中的日期范围来精准匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 13:32:39