rmdir.cn

db.collection.updateOne()

更新单个文档

语法

db.collection.updateOne(<filter>, <update>, <options>)

说明

更新匹配过滤条件的第一条文档。支持更新操作符($set、$inc、$push 等)。使用 upsert 选项可在不存在时插入。

参数

  • filter必填

    过滤条件,匹配要更新的文档

  • update必填

    更新操作符,如 { $set: { field: value } }

  • upsert

    true 表示不存在时插入新文档

示例

$set 更新字段

更新指定用户的邮箱

db.users.updateOne({ _id: ObjectId("...") }, { $set: { email: "new@example.com" } })

$inc 自增

增加用户的积分

db.users.updateOne({ _id: userId }, { $inc: { points: 10 } })

upsert 操作

不存在则插入

db.users.updateOne({ username: "admin" }, { $set: { role: "admin" } }, { upsert: true })