Learn

While updating a single document using a single field is helpful, MongoDB also stores data inside of embedded documents. So, what if we want to update a specific field in an embedded document? Consider the following document within a collection named furniture:

{ _id: ObjectId("3ldh1fg733kf65d7994393ld"), name: "bedframe", dimensions: { length: 75, width: 38 } }

Let’s say we wanted to update the width field inside the dimensions embedded document. We could run the following command:

db.furniture.updateOne( { name: "bedframe" }, { $set: { "dimensions.width": 54 }} );

We can successfully target the width field inside the dimensions embedded document using dot notation.

MongoDB also stores data inside of arrays! If we instead want to update a value within an array, we can use dot notation to access the index of the element we want to update. Let’s look at the following example document for a collection named nbateams:

{ _id: ObjectId("402h1fg73cf865d799439k42"), team: "Chicago Bulls", championships: [1991, 1902, 1993, 1996, 1997, 1998] }

If we want to update the 2nd element (1902) of the championships array to the correct year, 1992, we could run the following command:

db.nbateams.updateOne( { team: "Chicago Bulls" }, { $set: {"championships.1": 1992 }} )

Once again, the embedded document’s name and the array index must be wrapped in quotations for the command to be successful. Note that we’re using the index of 1 since the year 1902 is the second element of the array, and arrays start at index 0.

Let’s practice updating embedded fields and arrays in our restaurants database!

Instructions

1.

Connect to the restaurants database. Then, using the listingsAndReviews collection, query for a document with a restaurant_id field with the value"40561796". Observe the properties of the document you find!

2.

The street address for this restaurant is incorrect. Update the street value from "36 Street" to "58 street".

3.

Query the collection using the findOne() method for the document that was just updated to confirm this information was updated correctly.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?