您的位置:宽带测速网 > 网络知识 > mongodb怎么修改字段值

mongodb怎么修改字段值

2025-06-17 09:06来源:互联网 [ ]

要修改MongoDB中的字段值,您可以使用update()方法或findOneAndUpdate()方法。

    使用update()方法:
db.collection.update( { <query> }, { $set: { <field1>: <value1>, <field2>: <value2>, ... } })

示例:

db.collection.update( { _id: ObjectId("12345") }, { $set: { name: "John", age: 30 } })
    使用findOneAndUpdate()方法:
db.collection.findOneAndUpdate( { <query> }, { $set: { <field1>: <value1>, <field2>: <value2>, ... } })

示例:

db.collection.findOneAndUpdate( { _id: ObjectId("12345") }, { $set: { name: "John", age: 30 } })

请注意,update()方法会更新所有符合条件的文档,而findOneAndUpdate()方法只会更新第一个符合条件的文档。