文档菜单
文档首页
/
MongoDB for VS Code
/ /

使用 VS Code 更新文档

本页内容

  • 先决条件
  • 更新单个文档
  • 更新多个文档

您可以使用以下方式在集合中更新文档MongoDB CRUD 操作符 在 MongoDB 沙盒中

  • 使用 updateOne() 方法来更新单个文档。

  • 使用 updateMany() 方法来更新多个文档。

如果您还没有这样做,您必须在使用 MongoDB Playground 更新文档之前完成以下先决条件。

  • 连接到 MongoDB 部署.

  • 激活 MongoDB 部署的连接.

  • 打开 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 视图的右上角。VS Code 扩展将您的 Playground 和输出结果到 Playground Results.json 面板。如果您禁用了分割视图,VS Code 扩展在新的选项卡中输出 Playground 的结果。

以下示例

  1. 切换到测试数据库。

  2. 更新匹配过滤器的测试.sales集合中的一个文档。

use("test");
db.sales.updateOne(
{ "_id" : 1},
{ $inc: { "quantity" : 1 }}
);

当您按下播放按钮时,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视图右上角的播放按钮VS Code 扩展将您的 Playground 和输出结果到 Playground Results.json 面板。如果您禁用了分割视图,VS Code 扩展在新的选项卡中输出 Playground 的结果。

以下示例

  1. 切换到测试数据库。

  2. 更新匹配过滤条件的 test.sales 集合中的所有文档。

use("test");
db.sales.updateMany(
{ "item" : "abc" },
{ $set: { "price": 9 }}
);

当您按下播放按钮时,VS Code 扩展将您的Playground拆分并输出以下文档到Playground Results.json面板。如果您禁用了分割视图,VS Code 扩展将在新标签页中输出以下文档。如果您手动移动您的Playground结果,VS Code 扩展将在该标签页中显示结果。

{
acknowleged: 1,
matchedCount: 3,
modifiedCount: 3,
upsertedCount: 0,
insertedId: null
}

返回

读取