使用VS Code更新文档
您可以在 MongoDB Playground 中使用 MongoDB CRUD 操作符更新集合中的文档:
使用updateOne()方法更新一个文档。
使用updateMany()方法更新多个文档。
先决条件
如果尚未执行此操作,则必须先完成以下先决条件,然后才能使用 MongoDB Playground 更新文档:
使用VS Code创建文档,或使用其他方法在集合中创建文档。
更新一个文档
要更新一个文档,请在 Playground 中使用以下语法:
db.collection.updateOne( <filter>, <update>, { upsert: <boolean>, writeConcern: <document>, collation: <document>, arrayFilters: [ <filterdocument1>, ... ], hint: <document|string> } )
有关此方法参数的详细说明,请参阅 MongoDB 手册中的updateOne() 。
要运行 Playground,请按下 Playground 视图右上角的 Play Button。VS Code 扩展会拆分 Playground 并在 Playground Results.json 窗格中输出 Playground 的结果。如果已禁用分割视图,VS Code 扩展将在新的标签页中输出 Playground 的结果。
例子
如下示例:
切换到
test
数据库。在
test.sales
collection中更新与筛选器匹配的一个文档。
use("test"); db.sales.updateOne( { "_id" : 1}, { $inc: { "quantity" : 1 }} );
当您按 Play Button 时,VS Code 扩展会拆分您的 Playground 并在 Playground Results.json 窗格中输出以下文档。如果已禁用分割视图,VS Code 扩展则会在新的标签页中输出以下文档。如果手动移动 Playground 结果,VS Code 扩展将在该标签页中显示结果。
{ acknowleged: 1, matchedCount: 1, modifiedCount: 1, upsertedCount: 0, insertedId: null }
更新多个文档
要更新多个文档,请在 Playground 中使用以下语法:
db.collection.updateMany( <filter>, <update>, { upsert: <boolean>, writeConcern: <document>, collation: <document>, arrayFilters: [ <filterdocument1>, ... ], hint: <document|string> } )
有关此方法参数的详细说明,请参阅 MongoDB 手册中的updateMany() 。
要运行 Playground,请按下 Playground 视图右上角的 Play Button。VS Code 扩展会拆分 Playground 并在 Playground Results.json 窗格中输出 Playground 的结果。如果已禁用分割视图,VS Code 扩展将在新的标签页中输出 Playground 的结果。
例子
如下示例:
切换到
test
数据库。更新
test.sales
集合中与筛选器匹配的所有文档。
use("test"); db.sales.updateMany( { "item" : "abc" }, { $set: { "price": 9 }} );
当您按 Play Button 时,VS Code 扩展会拆分您的 Playground 并在 Playground Results.json 窗格中输出以下文档。如果已禁用分割视图,VS Code 扩展则会在新的标签页中输出以下文档。如果手动移动 Playground 结果,VS Code 扩展将在该标签页中显示结果。
{ acknowleged: 1, matchedCount: 3, modifiedCount: 3, upsertedCount: 0, insertedId: null }