面试题答案
一键面试- 新文档构建规则:
- 在MongoDB的upsert操作中,如果要更新的文档不存在,新文档会基于更新操作中的修改器(如
$set
、$inc
等)所指定的字段和值来构建。如果没有使用修改器,而是直接指定字段和值,那么这些字段和值会构成新文档。
- 在MongoDB的upsert操作中,如果要更新的文档不存在,新文档会基于更新操作中的修改器(如
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
来自匹配条件,name
和age
来自$set
修改器指定的内容。如果不使用$set
修改器,直接写成{ name: 'John', age: 30 }
,同样会构建新文档{ _id: 1, name: 'John', age: 30 }
,_id
依然来自匹配条件。
- 在上述例子中,集合