Update Documents更新文档

On this page本页内容

You can update documents in a collection using the MongoDB CRUD Operators in a MongoDB Playground:您可以在MongoDB游乐场中使用MongoDB CRUD运算符更新集合中的文档:

If you have not done so already, you must complete the following prerequisites before you can update documents with a MongoDB Playground:如果您尚未完成此操作,则必须先完成以下先决条件,然后才能使用MongoDB Playground更新文档:

To update one document, use the following syntax in your Playground:要更新一个文档,请在您的游乐场中使用以下语法:

db.collection.updateOne(
   <filter>,
   <update>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ],
     hint:  <document|string>
           }
        )

For a detailed description of this method's parameters, see updateOne() in the MongoDB Manual.

To run your Playground, press the Play Button at the top right of the Playground View. MongoDB for VS Code outputs the results of your playground to the Output view in Visual Studio Code.

The following example:

  1. Switches to the test database.
  2. Updates one document in the test.sales collection that matches the filter.
use("test");
db.sales.updateOne(
  { "_id" : 1},
  { $inc: { "quantity" : 1 }}
);

When you press the Play Button, this operation outputs the following document to the Output view in Visual Studio Code:

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

To update many documents, use the following syntax in your Playground:要更新许多文档,请在您的游乐场中使用以下语法:

db.collection.updateMany(
   <filter>,
   <update>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ],
     hint:  <document|string>
           }
        )

For a detailed description of this method's parameters, see updateMany() in the MongoDB Manual.有关此方法参数的详细说明,请参阅MongoDB手册中的updateMany()

To run your Playground, press the Play Button at the top right of the Playground View. MongoDB for VS Code outputs the results of your playground to the Output view in Visual Studio Code.

The following example:

  1. Switches to the test database.
  2. Updates all documents in the test.sales collection that match the filter.
use("test");
db.sales.updateMany(
  { "item" : "abc" },
  { $set: { "price": 9 }}
);

When you press the Play Button, this operation outputs the following document to the Output view in Visual Studio Code:

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