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:

2 D铆as
12 Hrs
40 Min
9 Seg

Array Update Operators

15/30
Resources

How to manipulate arrays in MongoDB with update operators?

When working with databases, it is crucial to understand how to handle more complex data structures, such as arrays. MongoDB offers specific tools for updating and managing arrays in documents. In this content, we explore how to use these operators, specifically push and pull, to modify arrays efficiently.

What are the steps to configure the environment?

To begin with, it is essential to have a suitable environment. In this exercise, we worked with a software called Platzi Store and used a predefined dataset. Here are the basic steps:

  1. Create the working folder: Create a folder to organize the files.
  2. Set up the necessary files:
    • Dataset: Save the initial dataset in a dataset.mongodb file.
    • Query: Define a file named query.mongodb to make queries on the database without the need to constantly insert data.

How to add elements to an array with push?

The push operator is a powerful tool that allows you to add new elements to the end of an array within a specific document. Here is how you can use it:

db.inventory.updateOne( { _id: 4 }, { $push: { tags: "headphone" } })

In this example, the goal is to add "headphone" to the tags array of the document with _id: 4. This is useful to keep your database up to date without replacing existing data.

How to remove elements from an array with pull?

Just as push allows you to add, the pull operator is ideal for removing elements. It can be used to remove either a single element or several elements from an array. Here is the syntax to remove a single element:

db.inventory.updateMany( {}, { $pull: { tags: "book" } })

This operation removes "book" from all tags arrays in the database documents.

How to remove multiple elements using pull with in?

To remove multiple elements from an array, you can use a combination of pull and in. Here both "school" and "appliance" are removed from the arrays:

db.inventory.updateMany( {}, { $pull: { tags: { $in: ["school", "appliance"] } } } } })

This approach is particularly efficient for cleaning unwanted data from multiple documents at once.

Recommendations for maintaining a tidy database.

  • Always verify the data: Before executing operations, inspect the contents of your documents to ensure that critical information is not affected.
  • Use operators cautiously: Although powerful, push and pull operators should be applied with precision to avoid unnecessary alterations.
  • Maintain a test environment: Before applying changes in production, test your scripts in a secure environment to minimize risks.

With these tools and strategies, you will be able to manipulate arrays in your MongoDB databases more effectively and with confidence. Keep exploring and improving your skills!

Contributions 11

Questions 0

Sort by:

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

Por si necesitan insertar multiples valores adentro de un arreglo, lo pueden hacer de la siguiente manera:

use("platzi_store")

db.inventory.updateOne({_id: 4}, {
  $push: {
    tags:{
      $each:["headphone","wireless"]
    }
  }
})
db.inventory.find()

Modificadores del operador push

$each
Agrega m煤ltiples valores al campo de la matriz.
$slice
Limita el n煤mero de elementos de la matriz. Requiere el uso del modificador $each.
$sort
Ordena los elementos de la matriz. Requiere el uso del modificador $each.
$position
Especifica la ubicaci贸n en la matriz en la que insertar los nuevos elementos. Requiere el uso del modificador $each. Sin el modificador $position, el $push agrega los elementos al final de la matriz

Mas sobre Array Update operators

Con los siguientes operadores podremos modificar los documentos que dentro contengan un array:

  • $push: Agrega un elemento en el array.
  • $pull: Remueve todos los elementos del array que hagan match con un query especifico.
  • $in: Hace match con algunos de los valores especificados en un arreglo.

Valla, este profesor es muy pro, se le entiende muy bien, eso si prestar atencion con enfoque

Est谩 muy interesante el curso, al punto que me tiene trasnochando 馃槄

EL update many sin un query es como un SET sin un WHERE ? hay que ser cuidadosos con esto jeje

Array Update Operator

{ _id: 1, item: { name: "item ab", code: "123", description : "Single line description."    }, qty: 15, tags: [ "school", "book", "bag", "headphone", "appliance" ], },
{ _id: 2, item: { name: "item cd", code: "123", description : "First line\nSecond line"     }, qty: 20, tags: [ "appliance", "school", "book" ] },
{ _id: 3, item: { name: "item ij", code: "456", description : "Many spaces before     line" }, qty: 25, tags: [ "school", "book" ] },
{ _id: 4, item: { name: "item xy", code: "456", description : "Multiple\nline description"  }, qty: 30, tags: [ "electronics", "school" ] },
{ _id: 5, item: { name: "item mn", code: "000" }, qty: 20, tags: [ "appliance", "school" ] }, 

si queremos a帽adir un nuevo elemento a la propiedad de arreglo podemos hacerlo con el operador $push

db.inventory.updateOne(
  {
    _id: 4
  },
  {
    $push: {
      tags: "anything"
    }
  }
)

si queremos a帽adir varios elementos a la propiedad de arreglo podemos hacerlo con el operador $each

db.inventory.updateMany({},
  {
    $push: {
      tags: {
        $each: ["ele1", "ele2"]
      }
    }
  }
)

caso contrario, si queremos quitar un elemento de la propiedad de arreglo podemos hacerlo con el operador $pull

db.inventory.updateMany({},
  {
    $pull: {
      tags: "book"
    }
  }
)

si queremos quitar varios elementos de la propiedad de arreglo podemos hacerlo con el operador $in

db.inventory.updateMany({},
  {
    $pull: {
      tags: {
        $in: ["ele1", "ele2"]
      }
    }
  }
)

Resumiendo

$push: a帽ade un elemento a un arreglo
$each: a帽ade varios elementos a un arreglo
$pull: remueve un elemento de un arreglo
$in: remueve varios elementos de un arreglo

Otra forma de hacerlo:

db.inventory.updateMany(
  {},
  {
    //delete this elements in a array
    $pullAll: {
      tags: ["notebook", "pencil"],
    },
  }
);
El codigo para quien lo necesite copiar de forma rapida: ```js use("platzi_store") db.inventory.drop() db.inventory.insertMany([ { _id: 1, item: { name: "item ab", code: "123", description : "Single line description." }, qty: 15, tags: [ "school", "book", "bag", "headphone", "appliance" ], }, { _id: 2, item: { name: "item cd", code: "123", description : "First line\nSecond line" }, qty: 20, tags: [ "appliance", "school", "book" ] }, { _id: 3, item: { name: "item ij", code: "456", description : "Many spaces before line" }, qty: 25, tags: [ "school", "book" ] }, { _id: 4, item: { name: "item xy", code: "456", description : "Multiple\nline description" }, qty: 30, tags: [ "electronics", "school" ] }, { _id: 5, item: { name: "item mn", code: "000" }, qty: 20, tags: [ "appliance", "school" ] }, ]) db.inventory.find() ```
Hola Chicos \n Yo me quise seguir con el escenario anterior en Docker sobre una IT Stores de Dispositivos technicos como : Laptops , HeadPhones, Switches y Routers, por tanto me he creado un array de tiendas disponibles en mi Ciudad Captial para poder ejecrcer esta clase desde local en mi mongodb docker container , no desde Atlas conectado mas si conectado al contenedor que ya he levantado y No quiero tumbar ps asi practivo algode Docker tambien en mi OS. ahora mis Elementos Documentos quedan asi : ```js { "_id": ObjectId("6747a6105e57721f18a1474f"), "ProductName": "Airpods", "Price": 425, "Quantity": 35, "BogStores": [ "PepeSierra", "Calle127", "CityCenter", "ElDoradoMall", "Kra30", "SubaStation", "PortalAmericas", "Calle54", "ChapineroPlazaq" ] } ```{ "\_id": ObjectId("6747a6105e57721f18a1474f"), "ProductName": "Airpods", "Price": 425, "Quantity": 35, "BogStores": \[ "PepeSierra", "Calle127", "CityCenter", "ElDoradoMall", "Kra30", "SubaStation", "PortalAmericas", "Calle54", "ChapineroPlazaq" ] } \nLuego Ya pude hacer actualizaciones con $push && $pull y fue Genial. \nChatGTP me ayudo un poco tambien .
En el codigo insert copiado del gist del profesor tiene una coma de mas al final de tags del id 1. Eso me dio error al ejecutar el insert. ```js use("platzi_store") db.inventory.drop() db.inventory.insertMany([ { _id: 1, item: { name: "item ab", code: "123", description : "Single line description." }, qty: 15, tags: [ "school", "book", "bag", "headphone", "appliance" ], }, { _id: 2, item: { name: "item cd", code: "123", description : "First line\nSecond line" }, qty: 20, tags: [ "appliance", "school", "book" ] }, { _id: 3, item: { name: "item ij", code: "456", description : "Many spaces before line" }, qty: 25, tags: [ "school", "book" ] }, { _id: 4, item: { name: "item xy", code: "456", description : "Multiple\nline description" }, qty: 30, tags: [ "electronics", "school" ] }, { _id: 5, item: { name: "item mn", code: "000" }, qty: 20, tags: [ "appliance", "school" ] }, ]) db.inventory.find() ```