Update Documents
This page provides examples of how to update documents in using the following methods in the mongo shell:
-
db.collection.updateOne(<filter>, <update>, <options>)
-
db.collection.updateMany(<filter>, <update>, <options>)
-
db.collection.replaceOne(<filter>, <replacement>, <options>)
The examples on this page use the inventory
collection. To create and/or populate the inventory
collection, run the following:
db.inventory.insertMany( [
{ item: "canvas", qty: 100, size: { h: 28, w: 35.5, uom: "cm" }, status: "A" },
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "mat", qty: 85, size: { h: 27.9, w: 35.5, uom: "cm" }, status: "A" },
{ item: "mousepad", qty: 25, size: { h: 19, w: 22.85, uom: "cm" }, status: "P" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" },
{ item: "sketchbook", qty: 80, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "sketch pad", qty: 95, size: { h: 22.85, w: 30.5, uom: "cm" }, status: "A" }
] );
You can run the operation in the web shell below:
This page provides examples of how to update documents in MongoDB Compass.
The examples on this page use the inventory
collection. Populate the inventory
collection with the following documents:
[
{ item: "canvas", qty: 100, size: { h: 28, w: 35.5, uom: "cm" }, status: "A" },
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "mat", qty: 85, size: { h: 27.9, w: 35.5, uom: "cm" }, status: "A" },
{ item: "mousepad", qty: 25, size: { h: 19, w: 22.85, uom: "cm" }, status: "P" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" },
{ item: "sketchbook", qty: 80, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "sketch pad", qty: 95, size: { h: 22.85, w: 30.5, uom: "cm" }, status: "A" }
]
For instructions on inserting documents using MongoDB Compass, see Insert Documents.
This page provides examples of how to update documents using the following methods in the PyMongo Python driver:
The examples on this page use the inventory
collection. To create and/or populate the inventory
collection, run the following:
db.inventory.insert_many([
{"item": "canvas",
"qty": 100,
"size": {"h": 28, "w": 35.5, "uom": "cm"},
"status": "A"},
{"item": "journal",
"qty": 25,
"size": {"h": 14, "w": 21, "uom": "cm"},
"status": "A"},
{"item": "mat",
"qty": 85,
"size": {"h": 27.9, "w": 35.5, "uom": "cm"},
"status": "A"},
{"item": "mousepad",
"qty": 25,
"size": {"h": 19, "w": 22.85, "uom": "cm"},
"status": "P"},
{"item": "notebook",
"qty": 50,
"size": {"h": 8.5, "w": 11, "uom": "in"},
"status": "P"},
{"item": "paper",
"qty": 100,
"size": {"h": 8.5, "w": 11, "uom": "in"},
"status": "D"},
{"item": "planner",
"qty": 75,
"size": {"h": 22.85, "w": 30, "uom": "cm"},
"status": "D"},
{"item": "postcard",
"qty": 45,
"size": {"h": 10, "w": 15.25, "uom": "cm"},
"status": "A"},
{"item": "sketchbook",
"qty": 80,
"size": {"h": 14, "w": 21, "uom": "cm"},
"status": "A"},
{"item": "sketch pad",
"qty": 95,
"size": {"h": 22.85, "w": 30.5, "uom": "cm"},
"status": "A"}])
This page provides examples of how to update documents using the following methods in the Java Synchronous Driver:
The examples on this page use the inventory
collection. To create and/or populate the inventory
collection, run the following:
collection.insertMany(asList(
Document.parse("{ item: 'canvas', qty: 100, size: { h: 28, w: 35.5, uom: 'cm' }, status: 'A' }"),
Document.parse("{ item: 'journal', qty: 25, size: { h: 14, w: 21, uom: 'cm' }, status: 'A' }"),
Document.parse("{ item: 'mat', qty: 85, size: { h: 27.9, w: 35.5, uom: 'cm' }, status: 'A' }"),
Document.parse("{ item: 'mousepad', qty: 25, size: { h: 19, w: 22.85, uom: 'cm' }, status: 'P' }"),
Document.parse("{ item: 'notebook', qty: 50, size: { h: 8.5, w: 11, uom: 'in' }, status: 'P' }"),
Document.parse("{ item: 'paper', qty: 100, size: { h: 8.5, w: 11, uom: 'in' }, status: 'D' }"),
Document.parse("{ item: 'planner', qty: 75, size: { h: 22.85, w: 30, uom: 'cm' }, status: 'D' }"),
Document.parse("{ item: 'postcard', qty: 45, size: { h: 10, w: 15.25, uom: 'cm' }, status: 'A' }"),
Document.parse("{ item: 'sketchbook', qty: 80, size: { h: 14, w: 21, uom: 'cm' }, status: 'A' }"),
Document.parse("{ item: 'sketch pad', qty: 95, size: { h: 22.85, w: 30.5, uom: 'cm' }, status: 'A' }")
));
This page provides examples of how to update documents using the following methods in the MongoDB Node.js Driver:
The examples on this page use the inventory
collection. To create and/or populate the inventory
collection, run the following:
await db.collection('inventory').insertMany([
{
item: 'canvas',
qty: 100,
size: { h: 28, w: 35.5, uom: 'cm' },
status: 'A'
},
{
item: 'journal',
qty: 25,
size: { h: 14, w: 21, uom: 'cm' },
status: 'A'
},
{
item: 'mat',
qty: 85,
size: { h: 27.9, w: 35.5, uom: 'cm' },
status: 'A'
},
{
item: 'mousepad',
qty: 25,
size: { h: 19, w: 22.85, uom: 'cm' },
status: 'P'
},
{
item: 'notebook',
qty: 50,
size: { h: 8.5, w: 11, uom: 'in' },
status: 'P'
},
{
item: 'paper',
qty: 100,
size: { h: 8.5, w: 11, uom: 'in' },
status: 'D'
},
{
item: 'planner',
qty: 75,
size: { h: 22.85, w: 30, uom: 'cm' },
status: 'D'
},
{
item: 'postcard',
qty: 45,
size: { h: 10, w: 15.25, uom: 'cm' },
status: 'A'
},
{
item: 'sketchbook',
qty: 80,
size: { h: 14, w: 21, uom: 'cm' },
status: 'A'
},
{
item: 'sketch pad',
qty: 95,
size: { h: 22.85, w: 30.5, uom: 'cm' },
status: 'A'
}
]);
This page provides examples of how to update documents using the following methods in the MongoDB PHP Library:
The examples on this page use the inventory
collection. To create and/or populate the inventory
collection, run the following:
$insertManyResult = $db->inventory->insertMany([
[
'item' => 'canvas',
'qty' => 100,
'size' => ['h' => 28, 'w' => 35.5, 'uom' => 'cm'],
'status' => 'A',
],
[
'item' => 'journal',
'qty' => 25,
'size' => ['h' => 14, 'w' => 21, 'uom' => 'cm'],
'status' => 'A',
],
[
'item' => 'mat',
'qty' => 85,
'size' => ['h' => 27.9, 'w' => 35.5, 'uom' => 'cm'],
'status' => 'A',
],
[
'item' => 'mousepad',
'qty' => 25,
'size' => ['h' => 19, 'w' => 22.85, 'uom' => 'cm'],
'status' => 'P',
],
[
'item' => 'notebook',
'qty' => 50,
'size' => ['h' => 8.5, 'w' => 11, 'uom' => 'in'],
'status' => 'P',
],
[
'item' => 'paper',
'qty' => 100,
'size' => ['h' => 8.5, 'w' => 11, 'uom' => 'in'],
'status' => 'D',
],
[
'item' => 'planner',
'qty' => 75,
'size' => ['h' => 22.85, 'w' => 30, 'uom' => 'cm'],
'status' => 'D',
],
[
'item' => 'postcard',
'qty' => 45,
'size' => ['h' => 10, 'w' => 15.25, 'uom' => 'cm'],
'status' => 'A',
],
[
'item' => 'sketchbook',
'qty' => 80,
'size' => ['h' => 14, 'w' => 21, 'uom' => 'cm'],
'status' => 'A',
],
[
'item' => 'sketch pad',
'qty' => 95,
'size' => ['h' => 22.85, 'w' => 30.5, 'uom' => 'cm'],
'status' => 'A',
],
]);
This page provides examples of how to update documents using the following methods in the Motor driver:
-
motor.motor_asyncio.AsyncIOMotorCollection.update_one()
-
motor.motor_asyncio.AsyncIOMotorCollection.update_many()
-
motor.motor_asyncio.AsyncIOMotorCollection.replace_one()
The examples on this page use the inventory
collection. To create and/or populate the inventory
collection, run the following:
await db.inventory.insert_many([
{"item": "canvas",
"qty": 100,
"size": {"h": 28, "w": 35.5, "uom": "cm"},
"status": "A"},
{"item": "journal",
"qty": 25,
"size": {"h": 14, "w": 21, "uom": "cm"},
"status": "A"},
{"item": "mat",
"qty": 85,
"size": {"h": 27.9, "w": 35.5, "uom": "cm"},
"status": "A"},
{"item": "mousepad",
"qty": 25,
"size": {"h": 19, "w": 22.85, "uom": "cm"},
"status": "P"},
{"item": "notebook",
"qty": 50,
"size": {"h": 8.5, "w": 11, "uom": "in"},
"status": "P"},
{"item": "paper",
"qty": 100,
"size": {"h": 8.5, "w": 11, "uom": "in"},
"status": "D"},
{"item": "planner",
"qty": 75,
"size": {"h": 22.85, "w": 30, "uom": "cm"},
"status": "D"},
{"item": "postcard",
"qty": 45,
"size": {"h": 10, "w": 15.25, "uom": "cm"},
"status": "A"},
{"item": "sketchbook",
"qty": 80,
"size": {"h": 14, "w": 21, "uom": "cm"},
"status": "A"},
{"item": "sketch pad",
"qty": 95,
"size": {"h": 22.85, "w": 30.5, "uom": "cm"},
"status": "A"}])
This page provides examples of how to update documents using the following methods in the Java Reactive Streams Driver:
-
com.mongodb.reactivestreams.client.MongoCollection.updateOne
-
com.mongodb.reactivestreams.client.MongoCollection.updateMany
-
com.mongodb.reactivestreams.client.MongoCollection.replaceOne
The examples on this page use the inventory
collection. To create and/or populate the inventory
collection, run the following:
Publisher<Success> insertManyPublisher = collection.insertMany(asList(
Document.parse("{ item: 'canvas', qty: 100, size: { h: 28, w: 35.5, uom: 'cm' }, status: 'A' }"),
Document.parse("{ item: 'journal', qty: 25, size: { h: 14, w: 21, uom: 'cm' }, status: 'A' }"),
Document.parse("{ item: 'mat', qty: 85, size: { h: 27.9, w: 35.5, uom: 'cm' }, status: 'A' }"),
Document.parse("{ item: 'mousepad', qty: 25, size: { h: 19, w: 22.85, uom: 'cm' }, status: 'P' }"),
Document.parse("{ item: 'notebook', qty: 50, size: { h: 8.5, w: 11, uom: 'in' }, status: 'P' }"),
Document.parse("{ item: 'paper', qty: 100, size: { h: 8.5, w: 11, uom: 'in' }, status: 'D' }"),
Document.parse("{ item: 'planner', qty: 75, size: { h: 22.85, w: 30, uom: 'cm' }, status: 'D' }"),
Document.parse("{ item: 'postcard', qty: 45, size: { h: 10, w: 15.25, uom: 'cm' }, status: 'A' }"),
Document.parse("{ item: 'sketchbook', qty: 80, size: { h: 14, w: 21, uom: 'cm' }, status: 'A' }"),
Document.parse("{ item: 'sketch pad', qty: 95, size: { h: 22.85, w: 30.5, uom: 'cm' }, status: 'A' }")
));
This page provides examples of how to update documents using the following methods in the MongoDB C# Driver:
The examples on this page use the inventory
collection. To create and/or populate the inventory
collection, run the following:
var documents = new[]
{
new BsonDocument
{
{ "item", "canvas" },
{ "qty", 100 },
{ "size", new BsonDocument { { "h", 28 }, { "w", 35.5 }, { "uom", "cm" } } },
{ "status", "A" }
},
new BsonDocument
{
{ "item", "journal" },
{ "qty", 25 },
{ "size", new BsonDocument { { "h", 14 }, { "w", 21 }, { "uom", "cm" } } },
{ "status", "A" }
},
new BsonDocument
{
{ "item", "mat" },
{ "qty", 85 },
{ "size", new BsonDocument { { "h", 27.9 }, { "w", 35.5 }, { "uom", "cm" } } },
{ "status", "A" }
},
new BsonDocument
{
{ "item", "mousepad" },
{ "qty", 25 },
{ "size", new BsonDocument { { "h", 19 }, { "w", 22.85 }, { "uom", "cm" } } },
{ "status", "P" }
},
new BsonDocument
{
{ "item", "notebook" },
{ "qty", 50 },
{ "size", new BsonDocument { { "h", 8.5 }, { "w", 11 }, { "uom", "in" } } },
{ "status", "P" } },
new BsonDocument
{
{ "item", "paper" },
{ "qty", 100 },
{ "size", new BsonDocument { { "h", 8.5 }, { "w", 11 }, { "uom", "in" } } },
{ "status", "D" }
},
new BsonDocument
{
{ "item", "planner" },
{ "qty", 75 },
{ "size", new BsonDocument { { "h", 22.85 }, { "w", 30 }, { "uom", "cm" } } },
{ "status", "D" }
},
new BsonDocument
{
{ "item", "postcard" },
{ "qty", 45 },
{ "size", new BsonDocument { { "h", 10 }, { "w", 15.25 }, { "uom", "cm" } } },
{ "status", "A" }
},
new BsonDocument
{
{ "item", "sketchbook" },
{ "qty", 80 },
{ "size", new BsonDocument { { "h", 14 }, { "w", 21 }, { "uom", "cm" } } },
{ "status", "A" }
},
new BsonDocument
{
{ "item", "sketch pad" },
{ "qty", 95 },
{ "size", new BsonDocument { { "h", 22.85 }, { "w", 30.5 }, { "uom", "cm" } } }, { "status", "A" } },
};
collection.InsertMany(documents);
This page provides examples of how to update documents using the following methods in the MongoDB Perl Driver:
The examples on this page use the inventory
collection. To create and/or populate the inventory
collection, run the following:
$db->coll("inventory")->insert_many(
[
{
item => "canvas",
qty => 100,
size => { h => 28, w => 35.5, uom => "cm" },
status => "A"
},
{
item => "journal",
qty => 25,
size => { h => 14, w => 21, uom => "cm" },
status => "A"
},
{
item => "mat",
qty => 85,
size => { h => 27.9, w => 35.5, uom => "cm" },
status => "A"
},
{
item => "mousepad",
qty => 25,
size => { h => 19, w => 22.85, uom => "cm" },
status => "P"
},
{
item => "notebook",
qty => 50,
size => { h => 8.5, w => 11, uom => "in" },
status => "P"
},
{
item => "paper",
qty => 100,
size => { h => 8.5, w => 11, uom => "in" },
status => "D"
},
{
item => "planner",
qty => 75,
size => { h => 22.85, w => 30, uom => "cm" },
status => "D"
},
{
item => "postcard",
qty => 45,
size => { h => 10, w => 15.25, uom => "cm" },
status => "A"
},
{
item => "sketchbook",
qty => 80,
size => { h => 14, w => 21, uom => "cm" },
status => "A"
},
{
item => "sketch pad",
qty => 95,
size => { h => 22.85, w => 30.5, uom => "cm" },
status => "A"
}
]
);
This page provides examples of how to update documents using the following methods in the MongoDB Ruby Driver:
The examples on this page use the inventory
collection. To create and/or populate the inventory
collection, run the following:
client[:inventory].insert_many([
{ item: 'canvas',
qty: 100,
size: { h: 28, w: 35.5, uom: 'cm' },
status: 'A' },
{ item: 'journal',
qty: 25,
size: { h: 14, w: 21, uom: 'cm' },
status: 'A' },
{ item: 'mat',
qty: 85,
size: { h: 27.9, w: 35.5, uom: 'cm' },
status: 'A' },
{ item: 'mousepad',
qty: 25,
size: { h: 19, w: 22.85, uom: 'cm' },
status: 'P' },
{ item: 'notebook',
qty: 50,
size: { h: 8.5, w: 11, uom: 'in' },
status: 'P' },
{ item: 'paper',
qty: 100,
size: { h: 8.5, w: 11, uom: 'in' },
status: 'D' },
{ item: 'planner',
qty: 75,
size: { h: 22.85, w: 30, uom: 'cm' },
status: 'D' },
{ item: 'postcard',
qty: 45,
size: { h: 10, w: 15.25, uom: 'cm' },
status: 'A' },
{ item: 'sketchbook',
qty: 80,
size: { h: 14, w: 21, uom: 'cm' },
status: 'A' },
{ item: 'sketch pad',
qty: 95,
size: { h: 22.85, w: 30.5, uom: 'cm' },
status: 'A' }
])
This page provides examples of how to update documents using the following methods in the MongoDB Scala Driver:
The examples on this page use the inventory
collection. To create and/or populate the inventory
collection, run the following:
collection.insertMany(Seq(
Document("""{ item: "canvas", qty: 100, size: { h: 28, w: 35.5, uom: "cm" }, status: "A" }"""),
Document("""{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" }"""),
Document("""{ item: "mat", qty: 85, size: { h: 27.9, w: 35.5, uom: "cm" }, status: "A" }"""),
Document("""{ item: "mousepad", qty: 25, size: { h: 19, w: 22.85, uom: "cm" }, status: "P" }"""),
Document("""{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" }"""),
Document("""{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" }"""),
Document("""{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" }"""),
Document("""{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }"""),
Document("""{ item: "sketchbook", qty: 80, size: { h: 14, w: 21, uom: "cm" }, status: "A" }"""),
Document("""{ item: "sketch pad", qty: 95, size: { h: 22.85, w: 30.5, uom: "cm" }, status: "A" }""")
)).execute()
更新集合中的文档
To update a document, MongoDB provides update operators, such as $set, to modify field values.
To use the update operators, pass to the update methods an update document of the form:
{
<update operator>: { <field1>: <value1>, ... },
<update operator>: { <field2>: <value2>, ... },
...
}
Some update operators, such as $set, will create the field if the field does not exist. See the individual update operator reference for details.
To update a document in Compass, hover over the target document and click the pencil icon:
After clicking the pencil icon, the document enters edit mode:
You can now change the this document by clicking the item you wish to change and modifying the value.
For detailed instructions on updating documents in Compass, refer to the Compass documentation or follow the example below.
Once you are satisfied with your changes, click Update to save the updated document.
Click Cancel to revert any modifications made to the document and exit edit mode.
To update a document, MongoDB provides update operators such as $set to modify field values.
To use the update operators, pass to the update methods an update document of the form:
{
<update operator>: { <field1>: <value1>, ... },
<update operator>: { <field2>: <value2>, ... },
...
}
Some update operators, such as $set, will create the field if the field does not exist. See the individual update operator reference for details.
To update a document, MongoDB provides update operators such as $set to modify field values.
The driver provides the com.mongodb.client.model.Updates class to facilitate the creation of update documents. For example:
combine(set( <field1>, <value1>), set(<field2>, <value2> ) )
For a list of the update helpers, see com.mongodb.client.model.Updates.
Some update operators, such as $set, will create the field if the field does not exist. See the individual update operator reference for details.
To update a document, MongoDB provides update operators such as $set to modify field values.
To use the update operators, pass to the update methods an update document of the form:
{
<update operator>: { <field1>: <value1>, ... },
<update operator>: { <field2>: <value2>, ... },
...
}
Some update operators, such as $set, will create the field if the field does not exist. See the individual update operator reference for details.
To update a document, MongoDB provides update operators such as $set to modify field values.
To use the update operators, pass to the update methods an update document of the form:
[
<update operator> => [ <field1> => <value1>, ... ],
<update operator> => [ <field2> => <value2>, ... ],
...
]
Some update operators, such as $set, will create the field if the field does not exist. See the individual update operator reference for details.
To update a document, MongoDB provides update operators such as $set to modify field values.
To use the update operators, pass to the update methods an update document of the form:
{
<update operator>: { <field1>: <value1>, ... },
<update operator>: { <field2>: <value2>, ... },
...
}
Some update operators, such as $set, will create the field if the field does not exist. See the individual update operator reference for details.
To update a document, MongoDB provides update operators such as $set to modify field values.
The driver provides the com.mongodb.client.model.Updates class to facilitate the creation of update documents. For example:
combine(set( <field1>, <value1>), set(<field2>, <value2> ) )
For a list of the update helpers, see com.mongodb.client.model.Updates.
Some update operators, such as $set, will create the field if the field does not exist. See the individual update operator reference for details.
To update a document, MongoDB provides update operators such as $set to modify field values.
To use the update operators, pass to the update methods an update document of the form:
{
<update operator> => { <field1> => <value1>, ... },
<update operator> => { <field2> => <value2>, ... },
...
}
Some update operators, such as $set, will create the field if the field does not exist. See the individual update operator reference for details.
To update a document, MongoDB provides update operators such as $set to modify field values.
To use the update operators, pass to the update methods an update document of the form:
{
<update operator> => { <field1> => <value1>, ... },
<update operator> => { <field2> => <value2>, ... },
...
}
Some update operators, such as $set, will create the field if the field does not exist. See the individual update operator reference for details.
To update a document, MongoDB provides update operators such as $set to modify field values.
To use the update operators, pass to the update methods an update document of the form:
{
<update operator> => { <field1> => <value1>, ... },
<update operator> => { <field2> => <value2>, ... },
...
}
Some update operators, such as $set, will create the field if the field does not exist. See the individual update operator reference for details.
To update a document, MongoDB provides update operators such as $set to modify field values.
To use the update operators, pass to the update methods an update document of the form:
(
set (<field1>, <value1>),
set (<field2>, <value2>),
...
)
Some update operators, such as $set, will create the field if the field does not exist. See the individual update operator reference for details.
更新单个文档
The following example uses the db.collection.updateOne() method on the inventory
collection to update the first document where item
equals "paper"
:
db.inventory.updateOne(
{ item: "paper" },
{
$set: { "size.uom": "cm", status: "P" },
$currentDate: { lastModified: true }
}
)
The update operation:
-
uses the $set operator to update the value of the
size.uom
field to"cm"
and the value of thestatus
field to"P"
, -
uses the $currentDate operator to update the value of the
lastModified
field to the current date. IflastModified
field does not exist, $currentDate will create the field. See $currentDate for details.
Update Multiple Documents
New in version 3.2.
The following example uses the db.collection.updateMany() method on the inventory
collection to update all documents where qty
is less than 50
:
db.inventory.updateMany(
{ "qty": { $lt: 50 } },
{
$set: { "size.uom": "in", status: "P" },
$currentDate: { lastModified: true }
}
)
The update operation:
-
uses the $set operator to update the value of the
size.uom
field to"in"
and the value of thestatus
field to"P"
, -
uses the $currentDate operator to update the value of the
lastModified
field to the current date. IflastModified
field does not exist, $currentDate will create the field. See $currentDate for details.
Replace a Document
To replace the entire content of a document except for the _id
field, pass an entirely new document as the second argument to db.collection.replaceOne().
When replacing a document, the replacement document must consist of only field/value pairs; i.e. do not include update operators expressions.
The replacement document can have different fields from the original document. In the replacement document, you can omit the _id
field since the _id
field is immutable; however, if you do include the _id
field, it must have the same value as the current value.
The following example replaces the first document from the inventory
collection where item: "paper"
:
db.inventory.replaceOne(
{ item: "paper" },
{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] }
)
The following example demonstrates using MongoDB Compass to modify a single document where item: paper
in the inventory
collection:
Note
This example uses the Compass Table View to modify the document. The editing process using the Compass List View follows a very similar approach.
For more information on the differences between Table View and List View in Compass, refer to the Compass documentation.
Modify the target document as follows:
-
Change the
status
field fromD
toP
. -
Change the
size.uom
field fromin
tocm
. -
Add a new field called
lastModified
whose value will be today's date. -
Click the Table button in the top navigation to access the Table View:
- Use the Compass query bar to locate the target document.
Copy the following filter document into the query bar and click Find:
{ item: "paper" }
- Hover over the
status
field and click the pencil icon which appears on the right side of the document to enter edit mode:
-
Change the value of the field to
"P"
. -
Click the Update button below the field to save your changes.
-
Hover over the
size
field and click the outward-pointing arrows which appear on the right side of the field. This opens a new tab which displays the fields within thesize
object:
-
Using the same process outlined in steps 3-5 for editing the
status
field, change the value of thesize.uom
field to"cm"
. -
Click the left-most tab above the table labelled
inventory
to return to the original table view, which displays the top-level document:
-
Hover over the
status
field and click the pencil icon which appears on the right side of the document to re-enter edit mode. -
Click inside of the
status
field and click the plus button icon which appears in the edit menu.
Click the Add Field After status button which appears below the plus button:
- Add a new field called
lastModified
with a value of today's date. Set the field type toDate
:
- Click the Update button below the field to save your changes.
Note
Because MongoDB Compass does not support $currentDate or any other Field Update Operators, you must manually enter the date value in Compass.
The following example uses the update_one() method on the inventory
collection to update the first document where item
equals "paper"
:
db.inventory.update_one(
{"item": "paper"},
{"$set": {"size.uom": "cm", "status": "P"},
"$currentDate": {"lastModified": True}})
Update Multiple Documents
New in version 3.2.
The following example uses the update_many() method on the inventory
collection to update all documents where qty
is less than 50
:
db.inventory.update_many(
{"qty": {"$lt": 50}},
{"$set": {"size.uom": "in", "status": "P"},
"$currentDate": {"lastModified": True}})
Replace a Document
To replace the entire content of a document except for the _id
field, pass an entirely new document as the second argument to replace_one().
When replacing a document, the replacement document must consist of only field/value pairs; i.e. do not include update operators expressions.
The replacement document can have different fields from the original document. In the replacement document, you can omit the _id
field since the _id
field is immutable; however, if you do include the _id
field, it must have the same value as the current value.
The following example replaces the first document from the inventory
collection where item: "paper"
:
db.inventory.replace_one(
{"item": "paper"},
{"item": "paper",
"instock": [
{"warehouse": "A", "qty": 60},
{"warehouse": "B", "qty": 40}]})
The following example uses the com.mongodb.client.MongoCollection.updateOne method on the inventory
collection to update the first document where item
equals "paper"
:
collection.updateOne(eq("item", "paper"),
combine(set("size.uom", "cm"), set("status", "P"), currentDate("lastModified")));
The update operation:
-
uses the $set operator to update the value of the
size.uom
field to"cm"
and the value of thestatus
field to"P"
, -
uses the $currentDate operator to update the value of the
lastModified
field to the current date. IflastModified
field does not exist, $currentDate will create the field. See $currentDate for details.
Update Multiple Documents
The following example uses the com.mongodb.client.MongoCollection.updateMany method on the inventory
collection to update all documents where qty
is less than 50
:
collection.updateMany(lt("qty", 50),
combine(set("size.uom", "in"), set("status", "P"), currentDate("lastModified")));
The update operation:
-
uses the $set operator to update the value of the
size.uom
field to"in"
and the value of thestatus
field to"P"
, -
uses the $currentDate operator to update the value of the
lastModified
field to the current date. IflastModified
field does not exist, $currentDate will create the field. See $currentDate for details.
Replace a Document
To replace the entire content of a document except for the _id
field, pass an entirely new document as the second argument to com.mongodb.client.MongoCollection.replaceOne.
When replacing a document, the replacement document must consist of only field/value pairs; i.e. do not include update operators expressions.
The replacement document can have different fields from the original document. In the replacement document, you can omit the _id
field since the _id
field is immutable; however, if you do include the _id
field, it must have the same value as the current value.
The following example replaces the first document from the inventory
collection where item: "paper"
:
collection.replaceOne(eq("item", "paper"),
Document.parse("{ item: 'paper', instock: [ { warehouse: 'A', qty: 60 }, { warehouse: 'B', qty: 40 } ] }"));
The following example uses the Collection.updateOne() method on the inventory
collection to update the first document where item
equals "paper"
:
await db.collection('inventory').updateOne(
{ item: 'paper' },
{
$set: { 'size.uom': 'cm', status: 'P' },
$currentDate: { lastModified: true }
}
);
The update operation:
-
uses the $set operator to update the value of the
size.uom
field to"cm"
and the value of thestatus
field to"P"
, -
uses the $currentDate operator to update the value of the
lastModified
field to the current date. IflastModified
field does not exist, $currentDate will create the field. See $currentDate for details.
Update Multiple Documents
The following example uses the Collection.updateMany() method on the inventory
collection to update all documents where qty
is less than 50
:
await db.collection('inventory').updateMany(
{ qty: { $lt: 50 } },
{
$set: { 'size.uom': 'in', status: 'P' },
$currentDate: { lastModified: true }
}
);
The update operation:
-
uses the $set operator to update the value of the
size.uom
field to"in"
and the value of thestatus
field to"P"
, -
uses the $currentDate operator to update the value of the
lastModified
field to the current date. IflastModified
field does not exist, $currentDate will create the field. See $currentDate for details.
Replace a Document
To replace the entire content of a document except for the _id
field, pass an entirely new document as the second argument to Collection.replaceOne().
When replacing a document, the replacement document must consist of only field/value pairs; i.e. do not include update operators expressions.
The replacement document can have different fields from the original document. In the replacement document, you can omit the _id
field since the _id
field is immutable; however, if you do include the _id
field, it must have the same value as the current value.
The following example replaces the first document from the inventory
collection where item: "paper"
:
await db.collection('inventory').replaceOne(
{ item: 'paper' },
{
item: 'paper',
instock: [
{ warehouse: 'A', qty: 60 },
{ warehouse: 'B', qty: 40 }
]
}
);
The following example uses the updateOne() method on the inventory
collection to update the first document where item
equals "paper"
:
$updateResult = $db->inventory->updateOne(
['item' => 'paper'],
[
'$set' => ['size.uom' => 'cm', 'status' => 'P'],
'$currentDate' => ['lastModified' => true],
]
);
The update operation:
-
uses the $set operator to update the value of the
size.uom
field to"cm"
and the value of thestatus
field to"P"
, -
uses the $currentDate operator to update the value of the
lastModified
field to the current date. IflastModified
field does not exist, $currentDate will create the field. See $currentDate for details.
Update Multiple Documents
The following example uses the updateMany() method on the inventory
collection to update all documents where qty
is less than 50
:
$updateResult = $db->inventory->updateMany(
['qty' => ['$lt' => 50]],
[
'$set' => ['size.uom' => 'cm', 'status' => 'P'],
'$currentDate' => ['lastModified' => true],
]
);
The update operation:
-
uses the $set operator to update the value of the
size.uom
field to"in"
and the value of thestatus
field to"P"
, -
uses the $currentDate operator to update the value of the
lastModified
field to the current date. IflastModified
field does not exist, $currentDate will create the field. See $currentDate for details.
Replace a Document
To replace the entire content of a document except for the _id
field, pass an entirely new document as the second argument to replaceOne().
When replacing a document, the replacement document must consist of only field/value pairs; i.e. do not include update operators expressions.
The replacement document can have different fields from the original document. In the replacement document, you can omit the _id
field since the _id
field is immutable; however, if you do include the _id
field, it must have the same value as the current value.
The following example replaces the first document from the inventory
collection where item: "paper"
:
$updateResult = $db->inventory->replaceOne(
['item' => 'paper'],
[
'item' => 'paper',
'instock' => [
['warehouse' => 'A', 'qty' => 60],
['warehouse' => 'B', 'qty' => 40],
],
]
);
The following example uses the update_one()
method on the inventory
collection to update the first document where item
equals "paper"
:
await db.inventory.update_one(
{"item": "paper"},
{"$set": {"size.uom": "cm", "status": "P"},
"$currentDate": {"lastModified": True}})
The update operation:
-
uses the $set operator to update the value of the
size.uom
field to"cm"
and the value of thestatus
field to"P"
, -
uses the $currentDate operator to update the value of the
lastModified
field to the current date. IflastModified
field does not exist, $currentDate will create the field. See $currentDate for details.
Update Multiple Documents
New in version 3.2.
The following example uses the update_many()
method on the inventory
collection to update all documents where qty
is less than 50
:
await db.inventory.update_many(
{"qty": {"$lt": 50}},
{"$set": {"size.uom": "in", "status": "P"},
"$currentDate": {"lastModified": True}})
The update operation:
-
uses the $set operator to update the value of the
size.uom
field to"in"
and the value of thestatus
field to"P"
, -
uses the $currentDate operator to update the value of the
lastModified
field to the current date. IflastModified
field does not exist, $currentDate will create the field. See $currentDate for details.
Replace a Document
To replace the entire content of a document except for the _id
field, pass an entirely new document as the second argument to replace_one()
.
When replacing a document, the replacement document must consist of only field/value pairs; i.e. do not include update operators expressions.
The replacement document can have different fields from the original document. In the replacement document, you can omit the _id
field since the _id
field is immutable; however, if you do include the _id
field, it must have the same value as the current value.
The following example replaces the first document from the inventory
collection where item: "paper"
:
await db.inventory.replace_one(
{"item": "paper"},
{"item": "paper",
"instock": [
{"warehouse": "A", "qty": 60},
{"warehouse": "B", "qty": 40}]})
The following example uses the com.mongodb.reactivestreams.client.MongoCollection.updateOne on the inventory
collection to update the first document where item
equals "paper"
:
Publisher<UpdateResult> updateOnePublisher = collection.updateOne(eq("item", "paper"),
combine(set("size.uom", "cm"), set("status", "P"), currentDate("lastModified")));
The update operation:
-
uses the $set operator to update the value of the
size.uom
field to"cm"
and the value of thestatus
field to"P"
, -
uses the $currentDate operator to update the value of the
lastModified
field to the current date. IflastModified
field does not exist, $currentDate will create the field. See $currentDate for details.
Update Multiple Documents
The following example uses the com.mongodb.reactivestreams.client.MongoCollection.updateMany method on the inventory
collection to update all documents where qty
is less than 50
:
Publisher<UpdateResult> updateManyPublisher = collection.updateMany(lt("qty", 50),
combine(set("size.uom", "in"), set("status", "P"), currentDate("lastModified")));
The update operation:
-
uses the $set operator to update the value of the
size.uom
field to"in"
and the value of thestatus
field to"P"
, -
uses the $currentDate operator to update the value of the
lastModified
field to the current date. IflastModified
field does not exist, $currentDate will create the field. See $currentDate for details.
Replace a Document
To replace the entire content of a document except for the _id
field, pass an entirely new document as the second argument to com.mongodb.reactivestreams.client.MongoCollection.replaceOne.
When replacing a document, the replacement document must consist of only field/value pairs; i.e. do not include update operators expressions.
The replacement document can have different fields from the original document. In the replacement document, you can omit the _id
field since the _id
field is immutable; however, if you do include the _id
field, it must have the same value as the current value.
The following example replaces the first document from the inventory
collection where item: "paper"
:
Publisher<UpdateResult> replaceOnePublisher = collection.replaceOne(eq("item", "paper"),
Document.parse("{ item: 'paper', instock: [ { warehouse: 'A', qty: 60 }, { warehouse: 'B', qty: 40 } ] }"));
The following example uses the IMongoCollection.UpdateOne() method on the inventory
collection to update the first document where item
equals "paper"
:
var filter = Builders<BsonDocument>.Filter.Eq("item", "paper");
var update = Builders<BsonDocument>.Update.Set("size.uom", "cm").Set("status", "P").CurrentDate("lastModified");
var result = collection.UpdateOne(filter, update);
The update operation:
-
uses the $set operator to update the value of the
size.uom
field to"cm"
and the value of thestatus
field to"P"
, -
uses the $currentDate operator to update the value of the
lastModified
field to the current date. IflastModified
field does not exist, $currentDate will create the field. See $currentDate for details.
Update Multiple Documents
The following example uses the IMongoCollection.UpdateMany() method on the inventory
collection to update all documents where qty
is less than 50
:
var filter = Builders<BsonDocument>.Filter.Lt("qty", 50);
var update = Builders<BsonDocument>.Update.Set("size.uom", "in").Set("status", "P").CurrentDate("lastModified");
var result = collection.UpdateMany(filter, update);
The update operation:
-
uses the $set operator to update the value of the
size.uom
field to"in"
and the value of thestatus
field to"P"
, -
uses the $currentDate operator to update the value of the
lastModified
field to the current date. IflastModified
field does not exist, $currentDate will create the field. See $currentDate for details.
Replace a Document
To replace the entire content of a document except for the _id
field, pass an entirely new document as the second argument to IMongoCollection.ReplaceOne().
When replacing a document, the replacement document must consist of only field/value pairs; i.e. do not include update operators expressions.
The replacement document can have different fields from the original document. In the replacement document, you can omit the _id
field since the _id
field is immutable; however, if you do include the _id
field, it must have the same value as the current value.
The following example replaces the first document from the inventory
collection where item: "paper"
:
var filter = Builders<BsonDocument>.Filter.Eq("item", "paper");
var replacement = new BsonDocument
{
{ "item", "paper" },
{ "instock", new BsonArray
{
new BsonDocument { { "warehouse", "A" }, { "qty", 60 } },
new BsonDocument { { "warehouse", "B" }, { "qty", 40 } } }
}
};
var result = collection.ReplaceOne(filter, replacement);
The following example uses the update_one() method on the inventory
collection to update the first document where item
equals "paper"
:
# For boolean values, use boolean.pm for 'true' and 'false'
$db->coll("inventory")->update_one(
{ item => "paper" },
{
'$set' => { "size.uom" => "cm", status => "P" },
'$currentDate' => { lastModified => true }
}
);
The update operation:
-
uses the $set operator to update the value of the
size.uom
field to"cm"
and the value of thestatus
field to"P"
, -
uses the $currentDate operator to update the value of the
lastModified
field to the current date. IflastModified
field does not exist, $currentDate will create the field. See $currentDate for details.
Update Multiple Documents
The following example uses the update_many() method on the inventory
collection to update all documents where qty
is less than 50
:
# For boolean values, use boolean.pm for 'true' and 'false'
$db->coll("inventory")->update_many(
{ qty => { '$lt' => 50 } },
{
'$set' => { "size.uom" => "in", status => "P" },
'$currentDate' => { lastModified => true }
}
);
The update operation:
-
uses the $set operator to update the value of the
size.uom
field to"in"
and the value of thestatus
field to"P"
, -
uses the $currentDate operator to update the value of the
lastModified
field to the current date. IflastModified
field does not exist, $currentDate will create the field. See $currentDate for details.
Replace a Document
To replace the entire content of a document except for the _id
field, pass an entirely new document as the second argument to replace_one().
When replacing a document, the replacement document must consist of only field/value pairs; i.e. do not include update operators expressions.
The replacement document can have different fields from the original document. In the replacement document, you can omit the _id
field since the _id
field is immutable; however, if you do include the _id
field, it must have the same value as the current value.
The following example replaces the first document from the inventory
collection where item: "paper"
:
$db->coll("inventory")->replace_one(
{ item => "paper" },
{
item => "paper",
instock => [ { warehouse => "A", qty => 60 }, { warehouse => "B", qty => 40 } ]
}
);
The following example uses the update_one() method on the inventory
collection to update the first document where item
equals "paper"
:
client[:inventory].update_one({ item: 'paper'},
{ '$set' => { 'size.uom' => 'cm', 'status' => 'P' },
'$currentDate' => { 'lastModified' => true } })
The update operation:
-
uses the $set operator to update the value of the
size.uom
field to"cm"
and the value of thestatus
field to"P"
, -
uses the $currentDate operator to update the value of the
lastModified
field to the current date. IflastModified
field does not exist, $currentDate will create the field. See $currentDate for details.
Update Multiple Documents
The following example uses the update_many() method on the inventory
collection to update all documents where qty
is less than 50
:
client[:inventory].update_many({ qty: { '$lt' => 50 } },
{ '$set' => { 'size.uom' => 'in', 'status' => 'P' },
'$currentDate' => { 'lastModified' => true } })
The update operation:
-
uses the $set operator to update the value of the
size.uom
field to"in"
and the value of thestatus
field to"P"
, -
uses the $currentDate operator to update the value of the
lastModified
field to the current date. IflastModified
field does not exist, $currentDate will create the field. See $currentDate for details.
Replace a Document
To replace the entire content of a document except for the _id
field, pass an entirely new document as the second argument to replace_one().
When replacing a document, the replacement document must consist of only field/value pairs; i.e. do not include update operators expressions.
The replacement document can have different fields from the original document. In the replacement document, you can omit the _id
field since the _id
field is immutable; however, if you do include the _id
field, it must have the same value as the current value.
The following example replaces the first document from the inventory
collection where item: "paper"
:
client[:inventory].replace_one({ item: 'paper' },
{ item: 'paper',
instock: [ { warehouse: 'A', qty: 60 },
{ warehouse: 'B', qty: 40 } ] })
The following example uses the updateOne() method on the inventory
collection to update the first document where item
equals "paper"
:
collection.updateOne(equal("item", "paper"),
combine(set("size.uom", "cm"), set("status", "P"), currentDate("lastModified"))
).execute()
The update operation:
-
uses the $set operator to update the value of the
size.uom
field to"cm"
and the value of thestatus
field to"P"
, -
uses the $currentDate operator to update the value of the
lastModified
field to the current date. IflastModified
field does not exist, $currentDate will create the field. See $currentDate for details.
Update Multiple Documents
The following example uses the updateMany() method on the inventory
collection to update all documents where qty
is less than 50
:
collection.updateMany(lt("qty", 50),
combine(set("size.uom", "in"), set("status", "P"), currentDate("lastModified"))
).execute()
The update operation:
-
uses the $set operator to update the value of the
size.uom
field to"in"
and the value of thestatus
field to"P"
, -
uses the $currentDate operator to update the value of the
lastModified
field to the current date. IflastModified
field does not exist, $currentDate will create the field. See $currentDate for details.
Replace a Document
To replace the entire content of a document except for the _id
field, pass an entirely new document as the second argument to replaceOne()
When replacing a document, the replacement document must consist of only field/value pairs; i.e. do not include update operators expressions.
The replacement document can have different fields from the original document. In the replacement document, you can omit the _id
field since the _id
field is immutable; however, if you do include the _id
field, it must have the same value as the current value.
The following example replaces the first document from the inventory
collection where item: "paper"
:
collection.replaceOne(equal("item", "paper"),
Document("""{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] }""")
).execute()
Behavior
Atomicity
MongoDB 中的所有写操作都是单个文档级别的原子操作。有关 MongoDB 和原子性的更多信息,请参阅原子性和 Transaction。
_id Field
设置后,您将无法更新_id
字段的值,也不能将现有文档替换为具有不同_id
字段值的替换文档。
Document Size
对于已弃用的 MMAPv1,当执行将文档大小增加到超过该文档分配空间的更新操作时,更新操作会将文档重新放置在磁盘上。
Field Order
在以下情况下,MongoDB 会在写操作之后保留文档字段的 Sequences* except *:
-
_id
字段始终是文档中的第一个字段。 -
包含renaming字段名称的更新可能会导致文档中字段的重新排序。
在 2.6 版中进行了更改:从 2.6 版开始,MongoDB 积极尝试保留文档中的字段 Sequences。在 2.6 版之前,MongoDB 并未主动保留文档中字段的 Sequences。
Upsert Option
If updateOne(), updateMany(), or replaceOne() includes upsert : true
and no documents match the specified filter, then the operation creates a new document and inserts it. If there are matching documents, then the operation modifies or replaces the matching document or documents.
For details on the new document created, see the individual reference pages for the methods.
Upsert Option
If update_one(), update_many(), or replace_one() includes upsert : true
and no documents match the specified filter, then the operation creates a new document and inserts it. If there are matching documents, then the operation modifies or replaces the matching document or documents.
For details on the new document created, see the individual reference pages for the methods.
Upsert Option
If the update and replace methods include the com.mongodb.client.model.UpdateOptions parameter that specifies com.mongodb.client.model.UpdateOptions.upsert(true) and no documents match the specified filter, then the operation creates a new document and inserts it. If there are matching documents, then the operation modifies or replaces the matching document or documents.
For details on the new document created, see the individual reference pages for the methods.
Upsert Option
If updateOne(), updateMany(), or replaceOne() include upsert : true
in the options
parameter document and no documents match the specified filter, then the operation creates a new document and inserts it. If there are matching documents, then the operation modifies or replaces the matching document or documents.
For details on the new document created, see the individual reference pages for the methods.
Upsert Option
If updateOne(), updateMany(), or replaceOne() includes upsert => true
and no documents match the specified filter, then the operation creates a new document and inserts it. If there are matching documents, then the operation modifies or replaces the matching document or documents.
For details on the new document created, see the individual reference pages for the methods.
Upsert Option
If update_one()
, update_many()
, or replace_one()
includes upsert : true
and no documents match the specified filter, then the operation creates a new document and inserts it. If there are matching documents, then the operation modifies or replaces the matching document or documents.
For details on the new document created, see the individual reference pages for the methods.
Upsert Option
If the update and replace methods include the UpdateOptions parameter that specifies UpdateOptions.upsert(true) and no documents match the specified filter, then the operation creates a new document and inserts it. If there are matching documents, then the operation modifies or replaces the matching document or documents.
For details on the new document created, see the individual reference pages for the methods.
Upsert Option
If UpdateOne(), UpdateMany(), or ReplaceOne() includes an UpdateOptions argument instance with the IsUpsert
option set to true
and no documents match the specified filter, then the operation creates a new document and inserts it. If there are matching documents, then the operation modifies or replaces the matching document or documents.
For details on the new document created, see the individual reference pages for the methods.
Upsert Option
If update_one(), update_many(), or replace_one() includes upsert => true
and no documents match the specified filter, then the operation creates a new document and inserts it. If there are matching documents, then the operation modifies or replaces the matching document or documents.
For details on the new document created, see the individual reference pages for the methods.
Upsert Option
If update_one(), update_many(), or replace_one() includes upsert => true
and no documents match the specified filter, then the operation creates a new document and inserts it. If there are matching documents, then the operation modifies or replaces the matching document or documents.
For details on the new document created, see the individual reference pages for the methods.
Upsert Option
If updateOne(), updateMany(), or replaceOne() includes upsert => true
and no documents match the specified filter, then the operation creates a new document and inserts it. If there are matching documents, then the operation modifies or replaces the matching document or documents.
For details on the new document created, see the individual reference pages for the methods.
Write Acknowledgement
对于写入问题,您可以指定从 MongoDB 请求的写入操作的确认级别。有关详细信息,请参见Write Concern。
See also
See also
-
motor.motor_asyncio.AsyncIOMotorCollection.update_one()
-
motor.motor_asyncio.AsyncIOMotorCollection.update_many()
-
motor.motor_asyncio.AsyncIOMotorCollection.replace_one()