MongoDB  插入文档

MongoDB 插入文档完整指南

(MongoDB 8.0+,2025 年最新实践)

核心结论
插入文档 = insertOne()insertMany()
自动创建集合 + 数据库,无需提前建表。


一、核心插入命令

命令用途返回
db.collection.insertOne(doc)插入 1 条 文档{ acknowledged: true, insertedId: ObjectId(...) }
db.collection.insertMany([doc1, doc2, ...])插入 多条 文档{ acknowledged: true, insertedIds: [id1, id2, ...] }

二、基本插入示例

// 1. 切换数据库(不存在自动创建)
use company

// 2. 插入单条文档(推荐)
db.employees.insertOne({
  name: "张三",
  age: 30,
  department: "技术部",
  skills: ["JavaScript", "MongoDB", "Node.js"],
  address: {
    city: "北京",
    zip: "100000"
  },
  isActive: true,
  hireDate: new Date("2023-05-15")
})

// 返回示例:
// { acknowledged: true, insertedId: ObjectId("671f2a1b9d8e4c2a7f1b3d5e") }
// 3. 插入多条文档
db.employees.insertMany([
  {
    name: "李四",
    age: 28,
    department: "产品部",
    skills: ["Python", "SQL"],
    hireDate: new Date("2024-01-10")
  },
  {
    name: "王五",
    age: 35,
    department: "技术部",
    skills: ["Go", "Docker", "K8s"],
    hireDate: new Date("2022-11-20")
  }
])

// 返回示例:
// {
//   acknowledged: true,
//   insertedIds: [
//     ObjectId("671f2a1b9d8e4c2a7f1b3d5f"),
//     ObjectId("671f2a1b9d8e4c2a7f1b3d60")
//   ]
// }

三、自动创建机制(关键!)

use ecommerce
db.products.insertOne({ name: "iPhone 16" })
// → 自动创建:ecommerce 数据库 + products 集合

无需

  • CREATE DATABASE
  • CREATE COLLECTION
  • 定义字段类型

四、_id 字段处理

情况行为
不写 _id自动生成 ObjectId
手动写 _id必须唯一,否则报错 Duplicate Key
批量插入含重复 _id整个操作失败(默认)
// 自定义 _id
db.users.insertOne({ _id: "U001", name: "管理员" })

// 批量插入,允许部分失败(ordered: false)
db.users.insertMany([
  { _id: 1, name: "A" },
  { _id: 2, name: "B" },
  { _id: 1, name: "C" }  // 重复,报错
], { ordered: false })

五、插入选项(options

选项说明示例
ordered是否按顺序插入(默认 true{ ordered: false }
bypassDocumentValidation跳过验证{ bypassDocumentValidation: true }
// 允许无序插入,部分失败不影响其他
db.logs.insertMany([
  { level: "info", msg: "启动" },
  { level: "error", msg: null },  // 违反验证
  { level: "warn", msg: "警告" }
], { 
  ordered: false,
  bypassDocumentValidation: true 
})

六、插入性能优化(大批量)

// 推荐:分批插入(每批 500~1000 条)
const batchSize = 1000;
const total = 100000;
let batch = [];

for (let i = 0; i < total; i++) {
  batch.push({
    index: i,
    value: Math.random(),
    createdAt: new Date()
  });

  if (batch.length === batchSize) {
    db.metrics.insertMany(batch, { ordered: false });
    batch = [];
  }
}

if (batch.length > 0) {
  db.metrics.insertMany(batch, { ordered: false });
}

七、验证插入成功

// 1. 查看文档数量
db.employees.countDocuments({})

// 2. 查看最新插入
db.employees.find().sort({ _id: -1 }).limit(3).pretty()

// 3. 统计部门人数
db.employees.aggregate([
  { $group: { _id: "$department", count: { $sum: 1 } } }
])

八、常见错误与解决方案

错误原因解决方案
E11000 duplicate key_id 重复确保唯一或使用 ordered: false
Document failed validation违反 validator检查 Schema 或加 bypassDocumentValidation
WriteConcernError写关注失败检查副本集状态
namespace not found集合不存在insert 会自动创建,无需担心

九、GUI 工具插入文档

工具操作
MongoDB Compass集合 → Add DataInsert Document
VS Code + MongoDB集合 → 右键 → Insert Document
MongoDB AtlasCollections → 集合 → Insert Document

十、完整插入脚本示例

// insert_data.js
use myapp

print("开始插入用户数据...")

// 插入管理员
const admin = db.users.insertOne({
  _id: "admin_001",
  name: "系统管理员",
  email: "admin@myapp.com",
  role: "superadmin",
  status: "active",
  createdAt: new Date(),
  preferences: { theme: "dark", lang: "zh" }
})

printjson(admin)

// 批量插入普通用户
const users = db.users.insertMany([
  { name: "张伟", email: "zhang@example.com", role: "user" },
  { name: "李娜", email: "li@example.com", role: "editor" },
  { name: "王磊", email: "wang@example.com", role: "user" }
], { ordered: false })

printjson(users)

print(`成功插入 ${users.insertedIds.length} 条用户数据`)
print("当前用户总数:", db.users.countDocuments({}))

运行:

mongosh insert_data.js

十一、一句话总结

**“MongoDB 插入文档 = insertOne() / insertMany() + **自动建库建表


快速插入模板

// 单条(开发)
db.posts.insertOne({ title: "Hello MongoDB", author: "我" })

// 批量(生产)
db.events.insertMany(arrayOf1000Docs, { ordered: false })

官方文档

  • https://www.mongodb.com/docs/manual/reference/method/db.collection.insertOne/
  • https://www.mongodb.com/docs/manual/reference/method/db.collection.insertMany/

如需 批量导入 CSV/JSON自增 ID 实现插入时自动加索引从 MySQL 迁移数据插入,欢迎继续提问!

文章已创建 2349

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部