更新文档
约 428 字大约 1 分钟
布欧-Lewyon
2026-05-15
首页 › MongoDB › CRUD 操作(在新窗口打开) › 更新文档
updateOne / updateMany
// 更新第一个匹配的文档
db.users.updateOne(
{ name: "Alice" },
{ $set: { age: 26 } }
)
// 更新所有匹配的文档
db.users.updateMany(
{ status: "inactive" },
{ $set: { status: "active", updatedAt: new Date() } }
)replaceOne
替换整个文档(除 _id 外):
db.users.replaceOne(
{ name: "Alice" },
{ name: "Alice", age: 26, email: "alice@new.com", role: "admin" }
)字段更新操作符
// $set:设置字段值
db.users.updateOne({ _id: 1 }, { $set: { email: "new@mail.com" } })
// $unset:删除字段
db.users.updateOne({ _id: 1 }, { $unset: { tempField: "" } })
// $inc:递增/递减
db.users.updateOne({ _id: 1 }, { $inc: { loginCount: 1, points: -10 } })
// $min / $max:条件更新
db.users.updateOne({ _id: 1 }, { $min: { discount: 0.8 } })
db.users.updateOne({ _id: 1 }, { $max: { score: 100 } })
// $mul:乘法
db.users.updateOne({ _id: 1 }, { $mul: { price: 1.1 } })
// $rename:重命名字段
db.users.updateOne({ _id: 1 }, { $rename: { "oldName": "newName" } })数组更新操作符
// $push:追加到数组
db.users.updateOne({ _id: 1 }, { $push: { tags: "senior" } })
db.users.updateOne({ _id: 1 }, {
$push: { logs: { $each: [1, 2, 3], $position: 0, $sort: -1, $slice: 10 } }
})
// $pull:删除匹配的元素
db.users.updateOne({ _id: 1 }, { $pull: { tags: "juniour" } })
// $pullAll:删除所有匹配的值
db.users.updateOne({ _id: 1 }, { $pullAll: { tags: ["old1", "old2"] } })
// $addToSet:集合添加(不重复)
db.users.updateOne({ _id: 1 }, { $addToSet: { tags: "developer" } })
// $pop:删除第一个(-1)或最后一个(1)
db.users.updateOne({ _id: 1 }, { $pop: { tags: -1 } })upsert
文档不存在时自动创建:
db.users.updateOne(
{ email: "new@user.com" },
{ $set: { name: "New User", createdAt: new Date() } },
{ upsert: true }
)
// 不存在 email 时,创建一个新文档,并返回 upsertedId批量更新
db.users.updateMany(
{ lastLogin: { $lt: new Date("2025-01-01") } },
{ $set: { status: "inactive" } }
)小结
updateOne/updateMany局部更新;replaceOne整个替换。$set设置字段,$unset删除字段,$inc递增。$push/$pull/$addToSet/$pop操作数组。upsert: true在文档不存在时自动创建。- 更新操作不返回修改后的文档(要获取需使用
findOneAndUpdate)。
