- Update Documents
- Update Documents in a Collection
- Update a Single Document
- Update Multiple Documents
- Update Multiple Documents
- Update Multiple Documents
- Update Multiple Documents
- Update Multiple Documents
- Update Multiple Documents
- Update Multiple Documents
- Update Multiple Documents
- Update Multiple Documents
- Update Multiple Documents
- Update Multiple Documents
- Update Multiple Documents
- Replace a Document
- Replace a Document
- Replace a Document
- Replace a Document
- Replace a Document
- Replace a Document
- Replace a Document
- Replace a Document
- Replace a Document
- Replace a Document
- Replace a Document
- Replace a Document
- Behavior
- Update Documents in a Collection
Update Documents
This page provides examples in:
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
This page uses the following mongo
shell methods:
db.collection.updateOne(<filter>, <update>, <options>)
db.collection.updateMany(<filter>, <update>, <options>)
db.collection.replaceOne(<filter>, <update>, <options>)
The examples on this page use theinventory
collection. To create and/or populate theinventory
collection, run the following:
This page uses MongoDB Compass toupdate the documents.
The examples on this page use the inventory
collection.Populate the inventory
collection with the followingdocuments:
This page uses thefollowing PyMongoPython driver methods:
pymongo.collection.Collection.update_one()
pymongo.collection.Collection.update_many()
pymongo.collection.Collection.replace_one()
The examples on this page use theinventory
collection. To create and/or populate theinventory
collection, run the following:
This page uses thefollowing Java Synchronous Driver methods:
- com.mongodb.client.MongoCollection.updateOne
- com.mongodb.client.MongoCollection.updateMany
- com.mongodb.client.MongoCollection.replaceOne
The examples on this page use theinventory
collection. To create and/or populate theinventory
collection, run the following:
This page uses thefollowing MongoDB Node.js Driver methods:
The examples on this page use theinventory
collection. To create and/or populate theinventory
collection, run the following:
This page uses thefollowing MongoDB PHP Library methods:
The examples on this page use theinventory
collection. To create and/or populate theinventory
collection, run the following:
This page uses thefollowing Motordriver methods:
motor.motor_asyncio.AsyncIOMotorCollection.update_one()
motor.motor_asyncio.AsyncIOMotorCollection.update_many()
motor.motor_asyncio.AsyncIOMotorCollection.replace_one()
The examples on this page use theinventory
collection. To create and/or populate theinventory
collection, run the following:
This page uses thefollowing Java Reactive Streams Driver methods:
- com.mongodb.reactivestreams.client.MongoCollection.updateOne)
- com.mongodb.reactivestreams.client.MongoCollection.updateMany)
- com.mongodb.reactivestreams.client.MongoCollection.replaceOne)
The examples on this page use theinventory
collection. To create and/or populate theinventory
collection, run the following:
This page uses thefollowing MongoDB C# Driver methods:
The examples on this page use theinventory
collection. To create and/or populate theinventory
collection, run the following:
This page uses thefollowing MongoDB Perl Driver methods:
- MongoDB::Collection::update_one()
- MongoDB::Collection::update_many()
- MongoDB::Collection::replace_one()
The examples on this page use theinventory
collection. To create and/or populate theinventory
collection, run the following:
This page uses thefollowing MongoDB Ruby Driver methods:
The examples on this page use theinventory
collection. To create and/or populate theinventory
collection, run the following:
This page uses thefollowing MongoDB Scala Driver methods:
- collection.updateOne():org.mongodb.scala.SingleObservable[org.mongodb.scala.result.UpdateResult])
- collection.updateMany():org.mongodb.scala.SingleObservable[org.mongodb.scala.result.UpdateResult])
- collection.replaceOne():org.mongodb.scala.SingleObservable[org.mongodb.scala.result.UpdateResult])
The examples on this page use theinventory
collection. To create and/or populate theinventory
collection, run the following:
This page uses thefollowing MongoDB Go Driver functions:
The examples on this page use theinventory
collection. To create and/or populate theinventory
collection, run the following:
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
- 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:
- [
- { 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, seeInsert Documents.
- 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"}])
- 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' }")
- ));
- 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'
- }
- ]);
- $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',
- ],
- ]);
- 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"}])
- 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' }")
- ));
- 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);
- $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"
- }
- ]
- );
- 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' }
- ])
- 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()
- docs := []interface{}{
- bson.D{
- {"item", "canvas"},
- {"qty", 100},
- {"size", bson.D{
- {"h", 28},
- {"w", 35.5},
- {"uom", "cm"},
- }},
- {"status", "A"},
- },
- bson.D{
- {"item", "journal"},
- {"qty", 25},
- {"size", bson.D{
- {"h", 14},
- {"w", 21},
- {"uom", "cm"},
- }},
- {"status", "A"},
- },
- bson.D{
- {"item", "mat"},
- {"qty", 85},
- {"size", bson.D{
- {"h", 27.9},
- {"w", 35.5},
- {"uom", "cm"},
- }},
- {"status", "A"},
- },
- bson.D{
- {"item", "mousepad"},
- {"qty", 25},
- {"size", bson.D{
- {"h", 19},
- {"w", 22.85},
- {"uom", "in"},
- }},
- {"status", "P"},
- },
- bson.D{
- {"item", "notebook"},
- {"qty", 50},
- {"size", bson.D{
- {"h", 8.5},
- {"w", 11},
- {"uom", "in"},
- }},
- {"status", "P"},
- },
- bson.D{
- {"item", "paper"},
- {"qty", 100},
- {"size", bson.D{
- {"h", 8.5},
- {"w", 11},
- {"uom", "in"},
- }},
- {"status", "D"},
- },
- bson.D{
- {"item", "planner"},
- {"qty", 75},
- {"size", bson.D{
- {"h", 22.85},
- {"w", 30},
- {"uom", "cm"},
- }},
- {"status", "D"},
- },
- bson.D{
- {"item", "postcard"},
- {"qty", 45},
- {"size", bson.D{
- {"h", 10},
- {"w", 15.25},
- {"uom", "cm"},
- }},
- {"status", "A"},
- },
- bson.D{
- {"item", "sketchbook"},
- {"qty", 80},
- {"size", bson.D{
- {"h", 14},
- {"w", 21},
- {"uom", "cm"},
- }},
- {"status", "A"},
- },
- bson.D{
- {"item", "sketch pad"},
- {"qty", 95},
- {"size", bson.D{
- {"h", 22.85},
- {"w", 30.5},
- {"uom", "cm"},
- }},
- {"status", "A"},
- },
- }
- result, err := coll.InsertMany(context.Background(), docs)
Update Documents in a Collection
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
To update a document, MongoDB providesupdate operators, suchas $set
, to modify field values.
To use the update operators, pass to the update methods anupdate document of the form:
- {
- <update operator>: { <field1>: <value1>, ... },
- <update operator>: { <field2>: <value2>, ... },
- ...
- }
Some update operators, such as $set
, will create the field ifthe field does not exist. See the individualupdate operator reference fordetails.
To update a document in Compass, hover over the targetdocument 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 tochange and modifying the value.
For detailed instructions on updating documents in Compass,refer to theCompass documentationor follow the example below.
Once you are satisfied with your changes, clickUpdate to save the updated document.
Click Cancel to revert any modifications made tothe document and exit edit mode.
To update a document, MongoDB providesupdate operators suchas $set
to modify field values.
To use the update operators, pass to the update methods anupdate document of the form:
- {
- <update operator>: { <field1>: <value1>, ... },
- <update operator>: { <field2>: <value2>, ... },
- ...
- }
Some update operators, such as $set
, will create the field ifthe field does not exist. See the individualupdate operator reference fordetails.
To update a document, MongoDB providesupdate operators suchas $set
to modify field values.
The driver provides the com.mongodb.client.model.Updatesclass 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 ifthe field does not exist. See the individualupdate operator reference fordetails.
To update a document, MongoDB providesupdate operators suchas $set
to modify field values.
To use the update operators, pass to the update methods anupdate document of the form:
- {
- <update operator>: { <field1>: <value1>, ... },
- <update operator>: { <field2>: <value2>, ... },
- ...
- }
Some update operators, such as $set
, will create the field ifthe field does not exist. See the individualupdate operator reference fordetails.
To update a document, MongoDB providesupdate operators suchas $set
to modify field values.
To use the update operators, pass to the update methods anupdate document of the form:
- [
- <update operator> => [ <field1> => <value1>, ... ],
- <update operator> => [ <field2> => <value2>, ... ],
- ...
- ]
Some update operators, such as $set
, will create the field ifthe field does not exist. See the individualupdate operator reference fordetails.
To update a document, MongoDB providesupdate operators suchas $set
to modify field values.
To use the update operators, pass to the update methods anupdate document of the form:
- {
- <update operator>: { <field1>: <value1>, ... },
- <update operator>: { <field2>: <value2>, ... },
- ...
- }
Some update operators, such as $set
, will create the field ifthe field does not exist. See the individualupdate operator reference fordetails.
To update a document, MongoDB providesupdate operators suchas $set
to modify field values.
The driver provides the com.mongodb.client.model.Updatesclass 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 ifthe field does not exist. See the individualupdate operator reference fordetails.
To update a document, MongoDB providesupdate operators suchas $set
to modify field values.
To use the update operators, pass to the update methods anupdate document of the form:
- {
- <update operator> => { <field1> => <value1>, ... },
- <update operator> => { <field2> => <value2>, ... },
- ...
- }
Some update operators, such as $set
, will create the field ifthe field does not exist. See the individualupdate operator reference fordetails.
To update a document, MongoDB providesupdate operators suchas $set
to modify field values.
To use the update operators, pass to the update methods anupdate document of the form:
- {
- <update operator> => { <field1> => <value1>, ... },
- <update operator> => { <field2> => <value2>, ... },
- ...
- }
Some update operators, such as $set
, will create the field ifthe field does not exist. See the individualupdate operator reference fordetails.
To update a document, MongoDB providesupdate operators suchas $set
to modify field values.
To use the update operators, pass to the update methods anupdate document of the form:
- {
- <update operator> => { <field1> => <value1>, ... },
- <update operator> => { <field2> => <value2>, ... },
- ...
- }
Some update operators, such as $set
, will create the field ifthe field does not exist. See the individualupdate operator reference fordetails.
To update a document, MongoDB providesupdate operators suchas $set
to modify field values.
To use the update operators, pass to the update methods anupdate document of the form:
- (
- set (<field1>, <value1>),
- set (<field2>, <value2>),
- ...
- )
Some update operators, such as $set
, will create the field ifthe field does not exist. See the individualupdate operator reference fordetails.
To update a document, MongoDB providesupdate operators suchas $set
to modify field values.
Some update operators, such as $set
, will create the field ifthe field does not exist. See the individualupdate operator reference fordetails.
Note
Starting in MongoDB 4.2, MongoDB can accept an aggregation pipelineto specify the modifications to make instead of an update document.See the method reference page for details.
Update a Single Document
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
The following example uses thedb.collection.updateOne()
method on theinventory
collection to update the first document whereitem
equals "paper"
:
The following example demonstrates using MongoDB Compass to modifya single document where item: paper
in the inventory
collection:
Note
This example uses the CompassTable View to modify thedocument. The editing process using the CompassList View follows a verysimilar approach.
For more information on the differences between Table Viewand List View in Compass, refer to theCompass documentation.
The following example uses theupdate_one()
method onthe inventory
collection to update the first documentwhere item
equals "paper"
:
The following example uses thecom.mongodb.client.MongoCollection.updateOne method on theinventory
collection to update the first document whereitem
equals "paper"
:
The following example uses theCollection.updateOne()method on the inventory
collection to update the _first_document where item
equals "paper"
:
The following example uses theupdateOne()
method on the inventory
collection to update the _first_document where item
equals "paper"
:
The following example uses theupdate_one()
method onthe inventory
collection to update the first documentwhere item
equals "paper"
:
The following example uses thecom.mongodb.reactivestreams.client.MongoCollection.updateOne)on the inventory
collection to update the first document whereitem
equals "paper"
:
The following example uses theIMongoCollection.UpdateOne() method on theinventory
collection to update the first document whereitem
equals "paper"
:
The following example uses theupdate_one() method on theinventory
collection to update the first document whereitem
equals "paper"
:
The following example uses theupdate_one() method on theinventory
collection to update the first document whereitem
equals "paper"
:
The following example uses theupdateOne():org.mongodb.scala.SingleObservable[org.mongodb.scala.result.UpdateResult])method on the inventory
collection to update the _first_document where item
equals "paper"
:
The following example uses theCollection.UpdateOne method on theinventory
collection to update the first document whereitem
equals "paper"
:
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
- 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 thesize.uom
field to"cm"
and the value of thestatus
field to"P"
, - uses the
$currentDate
operator to update the valueof thelastModified
field to the current date. IflastModified
field does not exist,$currentDate
will create the field. See$currentDate
for details.
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 willbe today’s date.Click the Table button in the top navigationto access the Table View:
- Use the Compass query bar tolocate the target document.
Copy the following filter document into the query bar and clickFind:
- { item: "paper" }
- Hover over the
status
field and click the pencil iconwhich appears on the right side of the document to enteredit mode:
Change the value of the field to
"P"
.Click the Update button below the field tosave your changes.
Hover over the
size
field and click theoutward-pointing arrows which appear on the right side ofthe field. This opens a new tab which displays the fieldswithin thesize
object:
Using the same process outlined in steps 3-5 for editing the
status
field, change the value of thesize.uom
fieldto"cm"
.Click the left-most tab above the table labelled
inventory
to return to the original table view, whichdisplays the top-level document:
Hover over the
status
field and click the pencil iconwhich appears on the right side of the document to re-enteredit mode.Click inside of the
status
field and click theplus button icon which appears in the edit menu.
Click the Add Field After status button whichappears below the plus button:
- Add a new field called
lastModified
with a value oftoday’s date. Set the field type toDate
:
- Click the Update button below the field tosave your changes.
Note
Because MongoDB Compass does not support$currentDate
or any otherField Update Operators,you must manually enter the date value in Compass.
- db.inventory.update_one(
- {"item": "paper"},
- {"$set": {"size.uom": "cm", "status": "P"},
- "$currentDate": {"lastModified": True}})
- 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 thesize.uom
field to"cm"
and the value of thestatus
field to"P"
, - uses the
$currentDate
operator to update the valueof thelastModified
field to the current date. IflastModified
field does not exist,$currentDate
will create the field. See$currentDate
for details.
- 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 thesize.uom
field to"cm"
and the value of thestatus
field to"P"
, - uses the
$currentDate
operator to update the valueof thelastModified
field to the current date. IflastModified
field does not exist,$currentDate
will create the field. See$currentDate
for details.
- $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 thesize.uom
field to"cm"
and the value of thestatus
field to"P"
, - uses the
$currentDate
operator to update the valueof thelastModified
field to the current date. IflastModified
field does not exist,$currentDate
will create the field. See$currentDate
for details.
- 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 thesize.uom
field to"cm"
and the value of thestatus
field to"P"
, - uses the
$currentDate
operator to update the valueof thelastModified
field to the current date. IflastModified
field does not exist,$currentDate
will create the field. See$currentDate
for details.
- 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 thesize.uom
field to"cm"
and the value of thestatus
field to"P"
, - uses the
$currentDate
operator to update the valueof thelastModified
field to the current date. IflastModified
field does not exist,$currentDate
will create the field. See$currentDate
for details.
- 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 thesize.uom
field to"cm"
and the value of thestatus
field to"P"
, - uses the
$currentDate
operator to update the valueof thelastModified
field to the current date. IflastModified
field does not exist,$currentDate
will create the field. See$currentDate
for details.
- # 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 thesize.uom
field to"cm"
and the value of thestatus
field to"P"
, - uses the
$currentDate
operator to update the valueof thelastModified
field to the current date. IflastModified
field does not exist,$currentDate
will create the field. See$currentDate
for details.
- 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 thesize.uom
field to"cm"
and the value of thestatus
field to"P"
, - uses the
$currentDate
operator to update the valueof thelastModified
field to the current date. IflastModified
field does not exist,$currentDate
will create the field. See$currentDate
for details.
- 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 thesize.uom
field to"cm"
and the value of thestatus
field to"P"
, - uses the
$currentDate
operator to update the valueof thelastModified
field to the current date. IflastModified
field does not exist,$currentDate
will create the field. See$currentDate
for details.
- result, err := coll.UpdateOne(
- context.Background(),
- bson.D{
- {"item", "paper"},
- },
- bson.D{
- {"$set", bson.D{
- {"size.uom", "cm"},
- {"status", "P"},
- }},
- {"$currentDate", bson.D{
- {"lastModified", true},
- }},
- },
- )
The update operation:
- uses the
$set
operator to update the value of thesize.uom
field to"cm"
and the value of thestatus
field to"P"
, - uses the
$currentDate
operator to update the valueof thelastModified
field to the current date. IflastModified
field does not exist,$currentDate
will create the field. See$currentDate
for details.
- Mongo Shell
- Python
- Java (Sync)
- Node.js
- PHP
- Other
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
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 whereqty
is less than 50
:
Update Multiple Documents
New in version 3.2.
The following example uses theupdate_many()
method onthe inventory
collection to update all documents whereqty
is less than 50
:
Update Multiple Documents
The following example uses thecom.mongodb.client.MongoCollection.updateMany method onthe inventory
collection to update all documents whereqty
is less than 50
:
Update Multiple Documents
The following example uses theCollection.updateMany()method on the inventory
collection to update all documentswhere qty
is less than 50
:
Update Multiple Documents
The following example uses theupdateMany()
method on the inventory
collection to update all documentswhere qty
is less than 50
:
Update Multiple Documents
New in version 3.2.
The following example uses theupdate_many()
method on the inventory
collection to update all documentswhere qty
is less than 50
:
Update Multiple Documents
The following example uses thecom.mongodb.reactivestreams.client.MongoCollection.updateMany)method on the inventory
collection to update all documents whereqty
is less than 50
:
Update Multiple Documents
The following example uses theIMongoCollection.UpdateMany()method on the inventory
collection to update all documentswhere qty
is less than 50
:
Update Multiple Documents
The following example uses theupdate_many() method onthe inventory
collection to update all documents whereqty
is less than 50
:
Update Multiple Documents
The following example uses theupdate_many() method onthe inventory
collection to update all documents whereqty
is less than 50
:
Update Multiple Documents
The following example uses theupdateMany():org.mongodb.scala.SingleObservable[org.mongodb.scala.result.UpdateResult]) method onthe inventory
collection to update all documents whereqty
is less than 50
:
Update Multiple Documents
The following example uses theCollection.UpdateManymethod on the inventory
collection to update all documentswhere qty
is less than 50
:
- Mongo Shell
- Python
- Java (Sync)
- Node.js
- PHP
- Other
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
- 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 thesize.uom
field to"in"
and the value of thestatus
field to"P"
, - uses the
$currentDate
operator to update the valueof thelastModified
field to the current date. IflastModified
field does not exist,$currentDate
will create the field. See$currentDate
for details.
- db.inventory.update_many(
- {"qty": {"$lt": 50}},
- {"$set": {"size.uom": "in", "status": "P"},
- "$currentDate": {"lastModified": True}})
- 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 thesize.uom
field to"in"
and the value of thestatus
field to"P"
, - uses the
$currentDate
operator to update the valueof thelastModified
field to the current date. IflastModified
field does not exist,$currentDate
will create the field. See$currentDate
for details.
- 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 thesize.uom
field to"in"
and the value of thestatus
field to"P"
, - uses the
$currentDate
operator to update the valueof thelastModified
field to the current date. IflastModified
field does not exist,$currentDate
will create the field. See$currentDate
for details.
- $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 thesize.uom
field to"in"
and the value of thestatus
field to"P"
, - uses the
$currentDate
operator to update the valueof thelastModified
field to the current date. IflastModified
field does not exist,$currentDate
will create the field. See$currentDate
for details.
- 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 thesize.uom
field to"in"
and the value of thestatus
field to"P"
, - uses the
$currentDate
operator to update the valueof thelastModified
field to the current date. IflastModified
field does not exist,$currentDate
will create the field. See$currentDate
for details.
- 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 thesize.uom
field to"in"
and the value of thestatus
field to"P"
, - uses the
$currentDate
operator to update the valueof thelastModified
field to the current date. IflastModified
field does not exist,$currentDate
will create the field. See$currentDate
for details.
- 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 thesize.uom
field to"in"
and the value of thestatus
field to"P"
, - uses the
$currentDate
operator to update the valueof thelastModified
field to the current date. IflastModified
field does not exist,$currentDate
will create the field. See$currentDate
for details.
- # 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 thesize.uom
field to"in"
and the value of thestatus
field to"P"
, - uses the
$currentDate
operator to update the valueof thelastModified
field to the current date. IflastModified
field does not exist,$currentDate
will create the field. See$currentDate
for details.
- 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 thesize.uom
field to"in"
and the value of thestatus
field to"P"
, - uses the
$currentDate
operator to update the valueof thelastModified
field to the current date. IflastModified
field does not exist,$currentDate
will create the field. See$currentDate
for details.
- 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 thesize.uom
field to"in"
and the value of thestatus
field to"P"
, - uses the
$currentDate
operator to update the valueof thelastModified
field to the current date. IflastModified
field does not exist,$currentDate
will create the field. See$currentDate
for details.
- result, err := coll.UpdateMany(
- context.Background(),
- bson.D{
- {"qty", bson.D{
- {"$lt", 50},
- }},
- },
- bson.D{
- {"$set", bson.D{
- {"size.uom", "cm"},
- {"status", "P"},
- }},
- {"$currentDate", bson.D{
- {"lastModified", true},
- }},
- },
- )
The update operation:
- uses the
$set
operator to update the value of thesize.uom
field to"in"
and the value of thestatus
field to"P"
, - uses the
$currentDate
operator to update the valueof thelastModified
field to the current date. IflastModified
field does not exist,$currentDate
will create the field. See$currentDate
for details.
- Mongo Shell
- Python
- Java (Sync)
- Node.js
- PHP
- Other
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
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 todb.collection.replaceOne()
.
When replacing a document, the replacement document must consist of onlyfield/value pairs; i.e. do not include update operators expressions.
The replacement document can have different fields from the originaldocument. In the replacement document, you can omit the _id
fieldsince 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 theinventory
collection where item: "paper"
:
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 toreplace_one()
.
When replacing a document, the replacement document must consist of onlyfield/value pairs; i.e. do not include update operators expressions.
The replacement document can have different fields from the originaldocument. In the replacement document, you can omit the _id
fieldsince 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 theinventory
collection where item: "paper"
:
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 tocom.mongodb.client.MongoCollection.replaceOne.
When replacing a document, the replacement document must consist of onlyfield/value pairs; i.e. do not include update operators expressions.
The replacement document can have different fields from the originaldocument. In the replacement document, you can omit the _id
fieldsince 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 theinventory
collection where item: "paper"
:
Replace a Document
To replace the entire content of a document except for the_id
field, pass an entirely new document as the secondargument toCollection.replaceOne().
When replacing a document, the replacement document must consist of onlyfield/value pairs; i.e. do not include update operators expressions.
The replacement document can have different fields from the originaldocument. In the replacement document, you can omit the _id
fieldsince 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 theinventory
collection where item: "paper"
:
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 toreplaceOne()
.
When replacing a document, the replacement document must consist of onlyfield/value pairs; i.e. do not include update operators expressions.
The replacement document can have different fields from the originaldocument. In the replacement document, you can omit the _id
fieldsince 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 theinventory
collection where item: "paper"
:
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 toreplace_one()
.
When replacing a document, the replacement document must consist of onlyfield/value pairs; i.e. do not include update operators expressions.
The replacement document can have different fields from the originaldocument. In the replacement document, you can omit the _id
fieldsince 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 theinventory
collection where item: "paper"
:
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 tocom.mongodb.reactivestreams.client.MongoCollection.replaceOne).
When replacing a document, the replacement document must consist of onlyfield/value pairs; i.e. do not include update operators expressions.
The replacement document can have different fields from the originaldocument. In the replacement document, you can omit the _id
fieldsince 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 theinventory
collection where item: "paper"
:
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 toIMongoCollection.ReplaceOne().
When replacing a document, the replacement document must consist of onlyfield/value pairs; i.e. do not include update operators expressions.
The replacement document can have different fields from the originaldocument. In the replacement document, you can omit the _id
fieldsince 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 theinventory
collection where item: "paper"
:
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 toreplace_one().
When replacing a document, the replacement document must consist of onlyfield/value pairs; i.e. do not include update operators expressions.
The replacement document can have different fields from the originaldocument. In the replacement document, you can omit the _id
fieldsince 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 theinventory
collection where item: "paper"
:
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 toreplace_one().
When replacing a document, the replacement document must consist of onlyfield/value pairs; i.e. do not include update operators expressions.
The replacement document can have different fields from the originaldocument. In the replacement document, you can omit the _id
fieldsince 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 theinventory
collection where item: "paper"
:
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 toreplaceOne():org.mongodb.scala.SingleObservable[org.mongodb.scala.result.UpdateResult])
When replacing a document, the replacement document must consist of onlyfield/value pairs; i.e. do not include update operators expressions.
The replacement document can have different fields from the originaldocument. In the replacement document, you can omit the _id
fieldsince 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 theinventory
collection where item: "paper"
:
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 toCollection.ReplaceOne.
When replacing a document, the replacement document must consist of onlyfield/value pairs; i.e. do not include update operators expressions.
The replacement document can have different fields from the originaldocument. In the replacement document, you can omit the _id
fieldsince 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 theinventory
collection where item: "paper"
:
- Mongo Shell
- Python
- Java (Sync)
- Node.js
- PHP
- Other
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
- db.inventory.replaceOne(
- { item: "paper" },
- { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] }
- )
- db.inventory.replace_one(
- {"item": "paper"},
- {"item": "paper",
- "instock": [
- {"warehouse": "A", "qty": 60},
- {"warehouse": "B", "qty": 40}]})
- collection.replaceOne(eq("item", "paper"),
- Document.parse("{ item: 'paper', instock: [ { warehouse: 'A', qty: 60 }, { warehouse: 'B', qty: 40 } ] }"));
- await db.collection('inventory').replaceOne(
- { item: 'paper' },
- {
- $set: {
- item: 'paper',
- instock: [{ warehouse: 'A', qty: 60 }, { warehouse: 'B', qty: 40 }]
- },
- $unset: {
- qty: '',
- size: '',
- status: '',
- lastModified: ''
- }
- }
- );
- $updateResult = $db->inventory->replaceOne(
- ['item' => 'paper'],
- [
- 'item' => 'paper',
- 'instock' => [
- ['warehouse' => 'A', 'qty' => 60],
- ['warehouse' => 'B', 'qty' => 40],
- ],
- ]
- );
- await db.inventory.replace_one(
- {"item": "paper"},
- {"item": "paper",
- "instock": [
- {"warehouse": "A", "qty": 60},
- {"warehouse": "B", "qty": 40}]})
- Publisher<UpdateResult> replaceOnePublisher = collection.replaceOne(eq("item", "paper"),
- Document.parse("{ item: 'paper', instock: [ { warehouse: 'A', qty: 60 }, { warehouse: 'B', qty: 40 } ] }"));
- 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);
- $db->coll("inventory")->replace_one(
- { item => "paper" },
- {
- item => "paper",
- instock => [ { warehouse => "A", qty => 60 }, { warehouse => "B", qty => 40 } ]
- }
- );
- client[:inventory].replace_one({ item: 'paper' },
- { item: 'paper',
- instock: [ { warehouse: 'A', qty: 60 },
- { warehouse: 'B', qty: 40 } ] })
- collection.replaceOne(equal("item", "paper"),
- Document("""{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] }""")
- ).execute()
- result, err := coll.ReplaceOne(
- context.Background(),
- bson.D{
- {"item", "paper"},
- },
- bson.D{
- {"item", "paper"},
- {"instock", bson.A{
- bson.D{
- {"warehouse", "A"},
- {"qty", 60},
- },
- bson.D{
- {"warehouse", "B"},
- {"qty", 40},
- },
- }},
- },
- )
Behavior
Atomicity
All write operations in MongoDB are atomic on the level of a singledocument. For more information on MongoDB and atomicity, seeAtomicity and Transactions.
_id Field
Once set, you cannot update the value of the _id
field nor can youreplace an existing document with a replacement document that has adifferent _id
field value.
Field Order
MongoDB preserves the order of the document fields following writeoperations except for the following cases:
- The
_id
field is always the first field in the document. - Updates that include
renaming
of field names mayresult in the reordering of fields in the document.
Changed in version 2.6: Starting in version 2.6, MongoDB actively attempts to preserve thefield order in a document. Before version 2.6, MongoDB did notactively preserve the order of the fields in a document.
- Mongo Shell
- Python
- Java (Sync)
- Node.js
- PHP
- Other
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
Upsert Option
If updateOne()
,updateMany()
, orreplaceOne()
includes upsert : true
andno documents match the specified filter, then the operation creates anew document and inserts it. If there are matching documents, then theoperation modifies or replaces the matching document or documents.
For details on the new document created, see the individual referencepages for the methods.
Upsert Option
If update_one()
,update_many()
, orreplace_one()
includesupsert : true
and no documents match the specifiedfilter, then the operation creates a new document and insertsit. If there are matching documents, then the operationmodifies or replaces the matching document or documents.
For details on the new document created, see the individual referencepages for the methods.
Upsert Option
If the update and replace methods include thecom.mongodb.client.model.UpdateOptions parameter thatspecifies com.mongodb.client.model.UpdateOptions.upsert(true)and no documents match the specified filter, then theoperation creates a new document and inserts it. If there arematching documents, then the operation modifies or replacesthe matching document or documents.
For details on the new document created, see the individual referencepages for the methods.
Upsert Option
If updateOne(),updateMany(), orreplaceOne() includeupsert : true
in the options
parameter document andno documents match the specified filter, then the operationcreates a new document and inserts it. If there are matchingdocuments, then the operation modifies or replaces the matchingdocument or documents.
For details on the new document created, see the individual referencepages for the methods.
Upsert Option
If updateOne()
,updateMany()
,or replaceOne()
includes upsert => true
and no documents match thespecified filter, then the operation creates a new document andinserts it. If there are matching documents, then the operationmodifies or replaces the matching document or documents.
For details on the new document created, see the individual referencepages for the methods.
Upsert Option
If update_one()
,update_many()
, orreplace_one()
includesupsert : true
and no documents match the specifiedfilter, then the operation creates a new document and insertsit. If there are matching documents, then the operationmodifies or replaces the matching document or documents.
For details on the new document created, see the individual referencepages for the methods.
Upsert Option
If the update and replace methods include theUpdateOptionsparameter that specifies UpdateOptions.upsert(true)and no documents match the specified filter, then theoperation creates a new document and inserts it. If there arematching documents, then the operation modifies or replacesthe matching document or documents.
For details on the new document created, see the individual referencepages for the methods.
Upsert Option
If UpdateOne(),UpdateMany(), orReplaceOne()includes an UpdateOptionsargument instance with the IsUpsert
option set to true
and no documents match the specified filter, then theoperation creates a new document and inserts it. If there arematching documents, then the operation modifies or replaces thematching document or documents.
For details on the new document created, see the individual referencepages for the methods.
Upsert Option
If update_one(),update_many(), orreplace_one() includesupsert => true
and no documents match the specifiedfilter, then the operation creates a new document and insertsit. If there are matching documents, then the operationmodifies or replaces the matching document or documents.
For details on the new document created, see the individual referencepages for the methods.
Upsert Option
If update_one(),update_many(), orreplace_one() includesupsert => true
and no documents match the specifiedfilter, then the operation creates a new document and insertsit. If there are matching documents, then the operationmodifies or replaces the matching document or documents.
For details on the new document created, see the individual referencepages for the methods.
Upsert Option
If updateOne():org.mongodb.scala.SingleObservable[org.mongodb.scala.result.UpdateResult]), updateMany():org.mongodb.scala.SingleObservable[org.mongodb.scala.result.UpdateResult]), or replaceOne():org.mongodb.scala.SingleObservable[org.mongodb.scala.result.UpdateResult])includes upsert => true
and no documents match the specifiedfilter, then the operation creates a new document and inserts it. Ifthere are matching documents, then the operation modifies or replacesthe matching document or documents.
For details on the new document created, see the individual referencepages for the methods.
Upsert Option
If Collection.UpdateOneincludes the Upsert option set to trueand no documents match thespecified filter, then the operation creates a new documentand inserts it. If there are matching documents, then theoperation modifies or replaces the matching document ordocuments.
For details on the new document created, see the individual referencepages for the methods.
Write Acknowledgement
With write concerns, you can specify the level of acknowledgementrequested from MongoDB for write operations. For details, seeWrite Concern.
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
See also
See also
See also
pymongo.collection.Collection.update_one()
pymongo.collection.Collection.update_many()
pymongo.collection.Collection.replace_one()
- Additional Methods
See also
- com.mongodb.client.MongoCollection.updateOne
- com.mongodb.client.MongoCollection.updateMany
- com.mongodb.client.MongoCollection.replaceOne
- Additional Java Synchronous Driver Write Examples
See also
See also
MongoDB\Collection::updateOne()
MongoDB\Collection::updateMany()
MongoDB\Collection::replaceOne()
- Additional Methods
See also
motor.motor_asyncio.AsyncIOMotorCollection.update_one()
motor.motor_asyncio.AsyncIOMotorCollection.update_many()
motor.motor_asyncio.AsyncIOMotorCollection.replace_one()
- Additional Methods
See also
- com.mongodb.reactivestreams.client.MongoCollection.updateOne)
- com.mongodb.reactivestreams.client.MongoCollection.updateMany)
- com.mongodb.reactivestreams.client.MongoCollection.replaceOne)
- Java Reactive Streams Driver Quick Tour
See also
- IMongoCollection.UpdateOne()
- IMongoCollection.UpdateMany()
- IMongoCollection.ReplaceOne()
- Additional Methods
See also
- MongoDB::Collection::update_one()
- MongoDB::Collection::update_many()
- MongoDB::Collection::replace_one()
- Additional Methods
See also
See also
- collection.updateOne():org.mongodb.scala.SingleObservable[org.mongodb.scala.result.UpdateResult])
- collection.updateMany():org.mongodb.scala.SingleObservable[org.mongodb.scala.result.UpdateResult])
- collection.replaceOne():org.mongodb.scala.SingleObservable[org.mongodb.scala.result.UpdateResult])
- Additional Methods
See also