MST
星途 面试题库

面试题:MongoDB中如何使用updateOne方法实现文档替换更新

在MongoDB里,假设有一个集合名为users,包含文档{name: 'Alice', age: 25},现在要将该文档整体替换为{name: 'Bob', age: 30},请写出使用updateOne方法实现此替换更新的代码。
44.9万 热度难度
数据库MongoDB

知识考点

AI 面试

面试题答案

一键面试
db.users.updateOne(
    {name: 'Alice', age: 25},
    {$set: {name: 'Bob', age: 30}},
    {upsert: false}
);

以上是JavaScript风格的MongoDB shell代码,若使用其他编程语言连接MongoDB数据库,具体语法会略有不同,但基本思路类似。例如在Python中使用pymongo库:

from pymongo import MongoClient

client = MongoClient()
db = client['your_database']
users = db['users']

users.update_one(
    {'name': 'Alice', 'age': 25},
    {'$set': {'name': 'Bob', 'age': 30}},
    upsert=False
)