MST

星途 面试题库

面试题:MongoDB更新操作中如何返回更新后的文档

在MongoDB中,使用更新操作时,若要返回更新后的文档,应如何实现?请给出相应的代码示例(以Node.js驱动为例)。
36.3万 热度难度
数据库MongoDB

知识考点

AI 面试

面试题答案

一键面试

在MongoDB的Node.js驱动中,要在更新操作时返回更新后的文档,可以使用findOneAndUpdate方法,并设置returnOriginal选项为false。以下是代码示例:

const { MongoClient } = require('mongodb');

// 连接到MongoDB
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);

async function updateDocument() {
    try {
        await client.connect();
        const database = client.db('test');
        const collection = database.collection('users');

        const filter = { name: 'John' };
        const update = { $set: { age: 30 } };
        const options = { returnOriginal: false };

        const result = await collection.findOneAndUpdate(filter, update, options);
        console.log(result.value);
    } finally {
        await client.close();
    }
}

updateDocument();

在上述代码中:

  1. filter定义了要更新的文档的筛选条件。
  2. update定义了具体的更新操作。
  3. options中的returnOriginal: false确保返回更新后的文档而不是原始文档。
  4. findOneAndUpdate方法执行更新操作并返回更新后的文档。