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

如何创建100个条目并保存至MongoDB数据库?附单条目创建代码

批量创建100个MongoDB条目并保存的实现方案

基于Mongoose的实现(推荐,若使用ODM)

假设你已有单个条目的Mongoose模型,批量插入的核心是使用Model.insertMany()方法,它能高效一次性插入多条数据,避免循环单条插入的性能损耗。

const YourModel = require('./models/YourModel'); // 替换为你的模型文件路径

// 生成100条匹配模型结构的测试数据
const batchItems = [];
for (let i = 1; i <= 100; i++) {
  batchItems.push({
    // 完全对齐你单个创建条目时的字段结构
    name: `test_item_${i}`,
    desc: `这是第${i}条批量生成的内容`,
    status: Math.random() > 0.5 ? 'active' : 'inactive' // 示例随机字段
  });
}

// 执行批量插入
async function runBatchInsert() {
  try {
    const insertResult = await YourModel.insertMany(batchItems);
    console.log(`成功批量插入 ${insertResult.length} 条数据`);
  } catch (error) {
    console.error('批量插入出错:', error);
    // 若需跳过错误条目、继续插入其余数据,添加参数:{ ordered: false }
    // await YourModel.insertMany(batchItems, { ordered: false });
  }
}

runBatchInsert();

基于原生MongoDB驱动的实现

如果直接使用原生驱动,逻辑类似,调用集合的insertMany()方法即可:

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

// 替换为你的MongoDB连接字符串、数据库名和集合名
const mongoUri = 'mongodb://localhost:27017';
const dbName = 'your_database_name';
const collectionName = 'your_collection_name';

async function batchInsert() {
  let client;
  try {
    client = await MongoClient.connect(mongoUri);
    const collection = client.db(dbName).collection(collectionName);

    // 生成100条数据
    const batchItems = [];
    for (let i = 1; i <= 100; i++) {
      batchItems.push({
        // 匹配你单个条目的字段结构
        title: `entry_${i}`,
        content: `批量生成的第${i}条内容`,
        createdAt: new Date()
      });
    }

    const result = await collection.insertMany(batchItems);
    console.log(`成功插入 ${result.insertedCount} 条数据`);
  } catch (err) {
    console.error('插入失败:', err);
  } finally {
    if (client) await client.close();
  }
}

batchInsert();

关键注意事项

  • 性能优化:insertMany()通过单次网络请求发送所有数据,比循环调用save()或insertOne()高效得多,尤其适合批量操作场景。
  • 错误控制:默认是有序插入,遇到错误会终止后续操作;若需跳过错误条目继续插入,添加{ ordered: false }参数。
  • 数据真实性:如果需要更真实的测试数据,可使用@faker-js/faker库生成随机姓名、邮箱等字段,安装后直接调用对应方法即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 15:06:29