-
Notifications
You must be signed in to change notification settings - Fork 0
05‐Replace and Delete Documents
To replace documents in MongoDB, we use the replaceOne() method. The replaceOne() method takes the following parameters:
-
filter: A query that matches the document to replace. -
replacement: The new document to replace the old one with. -
options: An object that specifies options for the update.
db.books.replaceOne(
{
_id: ObjectId("6282afeb441a74a98dbbec4e"),
},
{
title: "Data Science Fundamentals for Python and MongoDB",
isbn: "1484235967",
publishedDate: new Date("2018-5-10"),
thumbnailUrl:
"https://m.media-amazon.com/images/I/71opmUBc2wL._AC_UY218_.jpg",
authors: ["David Paper"],
categories: ["Data Science"],
}
)The updateOne() method accepts a filter document, an update document, and an optional options object.
The $set operator replaces the value of a field with the specified value, as shown in the following code:
db.podcasts.updateOne(
{
_id: ObjectId("5e8f8f8f8f8f8f8f8f8f8f8"),
},
{
$set: {
subscribers: 98562,
},
}
)The upsert option creates a new document if no documents match the filtered criteria. Here's an example:
db.podcasts.updateOne(
{ title: "The Developer Hub" },
{ $set: { topics: ["databases", "MongoDB"] } },
{ upsert: true }
)The $push operator adds a new value to the hosts array field. Here's an example:
db.podcasts.updateOne(
{ _id: ObjectId("5e8f8f8f8f8f8f8f8f8f8f8") },
{ $push: { hosts: "Nic Raboy" } }
)The findAndModify() method is used to find and replace a single document in MongoDB. It accepts a filter document, a replacement document, and an optional options object. The following code shows an example:
db.podcasts.findAndModify({
query: { _id: ObjectId("6261a92dfee1ff300dc80bf1") },
update: { $inc: { subscribers: 1 } },
new: true,
})To update multiple documents, use the updateMany() method. This method accepts a filter document, an update document, and an optional options object. The following code shows an example:
db.books.updateMany(
{ publishedDate: { $lt: new Date("2019-01-01") } },
{ $set: { status: "LEGACY" } }
)To delete documents, use the deleteOne() or deleteMany() methods. Both methods accept a filter document and an options object.
The following code shows an example of the deleteOne() method:
db.podcasts.deleteOne({ _id: Objectid("6282c9862acb966e76bbf20a") })The following code shows an example of the deleteMany() method:
db.podcasts.deleteMany({category: “crime”})