MST

星途 面试题库

面试题:MongoDB中upsert操作在更新文档时,若文档不存在会如何构建新文档

在MongoDB的upsert操作中,如果要更新的文档不存在,系统会依据什么规则构建新文档?请举例说明在使用`updateOne`方法结合upsert选项时,新文档的构建情况。
15.9万 热度难度
数据库MongoDB

知识考点

AI 面试

面试题答案

一键面试
  1. 新文档构建规则
    • 在MongoDB的upsert操作中,如果要更新的文档不存在,新文档会基于更新操作中的修改器(如$set$inc等)所指定的字段和值来构建。如果没有使用修改器,而是直接指定字段和值,那么这些字段和值会构成新文档。
  2. updateOne方法结合upsert选项新文档构建举例
    const { MongoClient } = require('mongodb');
    const uri = "mongodb://localhost:27017";
    const client = new MongoClient(uri);
    
    async function run() {
        try {
            await client.connect();
            const database = client.db('test');
            const collection = database.collection('testCollection');
    
            // 执行updateOne操作,upsert为true,如果文档不存在则创建新文档
            const result = await collection.updateOne(
                { _id: 1 }, // 匹配条件
                { $set: { name: 'John', age: 30 } }, // 更新操作,这里使用$set修改器
                { upsert: true }
            );
            console.log(result);
        } finally {
            await client.close();
        }
    }
    run().catch(console.dir);
    
    • 在上述例子中,集合testCollection中如果不存在_id为1的文档,由于upsert设置为true,系统会依据$set修改器构建一个新文档{ _id: 1, name: 'John', age: 30 }_id来自匹配条件,nameage来自$set修改器指定的内容。如果不使用$set修改器,直接写成{ name: 'John', age: 30 },同样会构建新文档{ _id: 1, name: 'John', age: 30 }_id依然来自匹配条件。