MongoDB 使用 (/)、(带操作符的 /)和 (/)方法来修改数据。更新使用 而不是替换整个文档 — 这是一个重要的区别。
MongoDB 使用 (/)、(带操作符的 /)和 (/)方法来修改数据。更新使用 而不是替换整个文档 — 这是一个重要的区别。
insertOneinsertManyupdateOneupdateManydeleteOnedeleteManydb.users.insertOne({ name: "Ann", age: 30 }); // → returns the inserted _id
db.users.insertMany([{ name: "Bob" }, { name: "Carol" }]); // bulk insert (efficient)
// updateOne — filter (which doc) + update (with OPERATORS)
db.users.updateOne(
{ name: "Ann" },
{ $set: { age: 31, status: "active" } } // $set: change specific fields
);
// common update operators
{ $set: { field: value } } // set/change a field
{ $unset: { field: "" } } // remove a field
{ $inc: { count: 1 } } // increment a number
{ $push: { tags: "new" } } // add to an array
{ $pull: { tags: "old" } } // remove from an array
{ $addToSet: { tags: "x" } } // add to array only if not present
db.users.updateMany({ active: false }, { $set: { archived: true } }); // update all matching
重要提示: 更新使用 操作符($set、$inc、$push 等)来修改 特定 字段。如果不使用操作符,你会 替换整个文档 — 这是一个常见的陷阱:
// ❌ this REPLACES the whole document (loses other fields!)
db.users.updateOne({ name: "Ann" }, { age: 31 }); // Ann now has ONLY age!
// ✅ use $set to change just the field
db.users.updateOne({ name: "Ann" }, { $set: { age: 31 } });
db.users.deleteOne({ name: "Ann" }); // delete the first match
db.users.deleteMany({ active: false }); // delete all matching
db.users.deleteMany({}); // ⚠️ deletes ALL documents!
db.users.updateOne(
{ email: "[email protected]" },
{ $set: { name: "Ann" } },
{ upsert: true } // if no match, INSERT a new document
);
插入、更新和删除操作是应用程序在 MongoDB 中 修改数据 的方式,对任何数据驱动型应用都是基础,因此理解这些操作是必要的日常知识。
掌握这些方法(使用 insertOne/insertMany 创建、使用 updateOne/updateMany 修改、使用 deleteOne/deleteMany 删除)涵盖了基础知识。
最重要且最容易犯错的一点 是 MongoDB 的更新使用 update 操作符($set、$inc、$push、$pull 等)来修改 特定 字段 — 而且至关重要的是,忘记使用操作符会替换整个文档(一个臭名昭著的陷阱,其中 updateOne({...}, {age: 31}) 会清除所有其他字段,仅保留 age),因此理解始终为字段级更新使用 $set(和其他操作符)对正确性至关重要。
掌握常用操作符($set、用于计数器的 $inc、用于数组的 $push/$pull/$addToSet — 数组操作符特别相关,因为 MongoDB 的文档富含数组)是重要的日常知识。
理解 upsert({ upsert: true } — 如果没有匹配则插入,MongoDB 的 insert-or-update 方式)对于常见的 insert-or-update 模式很有价值。
还值得注意的是 deleteMany({}) 的危险(删除所有内容 — 类似于 SQL 中缺少 WHERE 子句的危险)。
由于修改数据是基础,而且 MongoDB 的基于操作符的更新(带有文档替换陷阱)、数组操作符和 upsert 是你正确修改数据的方式,理解 insert/update/delete — 特别是关键的 update 操作符区别(避免意外的文档替换)— 对任何 MongoDB 开发都是必要的、必知的知识,其中操作符陷阱特别是实际 bugs 的常见来源。