You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
3 Hrs
3 Min
54 Seg
Curso de Base de Datos NoSQL

Curso de Base de Datos NoSQL

Adán Figueroa Jiménez

Adán Figueroa Jiménez

Cómo Actualizar Documentos en MongoDB

11/17
Resources

Modifying or updating documents in MongoDB is essential for handling dynamic data. Although there are several methods to perform these actions, the most common are update and replace. Each is used in different scenarios and it is crucial to understand their differences and applications.

How is update used in MongoDB?

What is update?

The update method allows you to modify certain values of a document that meet a specific filter. There are variants such as updateOne and updateMany.

How to use updateOne?

To update a single document in MongoDB, updateOne is used. This method requires a filter to identify the document and the $set operator to specify the changes. For example, to change the name of a customer:

db.customers.updateOne( { _id: ObjectId("5f3e5a3a3a29f1e8e8b7c2c69d62") }, { $set: { name: "Elizabeth" } } );

This command searches for the document with the specified _id and updates the name field.

How to use updateMany?

To update multiple documents that meet a criterion, updateMany is used. This method also requires a filter and the changes to be made:

{ db.customers.updateMany( { birthYear: { $gte: 1990 } }, { $set: { membership: { "Platinum" } } );

In this example, all documents where birthYear is greater than or equal to 1990 will be updated to include the membership field with the value Platinum.

What is replace in MongoDB?

How does replaceOne work?

The replaceOne method replaces an entire document except for its identifier. This is useful when you need to restructure a document:

db.customers.replaceOne( { _id: ObjectId("5f3e5a3a3a29f1e8e8b7c2c69d62") }, { name: "John Doe", age: 30, city: "New York" } );

This command replaces the document identified by _id with a new one that has the name, age and city fields.

What other alternatives are there to update and replace?

In addition to update and replace, MongoDB offers other methods for data manipulation, such as bulkWrite, which allows multiple operations to be performed in a single call, and findAndModify, which returns and modifies documents in a single step.

Practical Exercise

For further practice, try the following challenge: in the Airbnb database, update all apartments with less than three rooms by subtracting 10 from the price. This will help you apply the concepts you have learned.

db.airbnb.updateMany( { bedrooms: { $lt: 3 } }, { $inc: { price: -10 } } );

Contributions 6

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

El resultado del reto ```js db.rooms.updateMany( {bedrooms: {$lt: 3}}, [{ $set: { newprice: { $toDouble: { $max: [{$subtract: ["$price", 10]}, 0] } } } }] ) ```
Esto me funciono: ![](https://static.platzi.com/media/user_upload/image-99350310-f506-4af8-bfb2-a17e21230b61.jpg)
Oigan @teamplatzi , me parece que esta clase debe ir antes que la que tienen publicada como la clase 10.
Lo hice mal 😂, intenté usar el operador `$subtract`, pero convertí los precios en un Array, estoy viendo como utilizarlo bien. Creo que podría revertir el cambio si elimino `sample_airbnb` y lo vuelvo a descargar. ```js db.listingsAndReviews.updateMany( { property_type: { $in: ["Home", "Apartment"] }, bedrooms: { $gte: 3 } }, { $set: { price: { $subtract: ["$price", 10] } } } ); ``` ![](https://static.platzi.com/media/user_upload/image-4fac8b6e-541f-4762-8866-6f7df4d34e25.jpg) ![](https://static.platzi.com/media/user_upload/image-c2c92bb5-646d-4e4c-8a06-7077e2dc9faf.jpg)
```js db.listingsAndReviews.updateMany( {property_type: {$in: ["House", "Apartment"]}, bedrooms: {$lt: 3}}, {$inc: {price: - 10}} ); ```
Me pareció más óptima esta forma. ```js db.rooms.updateMany( { price: { $exists: true } }, // Condición: solo aplica a documentos que tengan el campo "price" { $inc: { price: -10 } } // Actualización: resta 10 al campo "price" ); ```