Learn

MongoDB provides different array update operators that we can use with the .updateOne() method. In the earlier exercises, we learned to use the $set operator to replace a value. In this exercise, we’ll look at the $push operator.

The $push operator adds (or “pushes”) new elements to the end of an array. It can be used with the .updateOne() method with the following syntax:

db.<collection>.updateOne( <filter>, { $push: { <field1>: <value1>, ... } } );

Consider a collection, automobiles, holding a document with data regarding specific car models:

{ _id: ObjectId("627934bbfd6a8619040cc287"), make: "Audi", model: "A1", year: [2017, 2019] }

If we wanted to add a new year into the array, we could use the $push operator to accomplish this:

db.vehicles.updateOne( { make: "Audi" }, { $push: { year: 2020 }} );

The updated document would look as follows:

{ _id: ObjectId("627934bbfd6a8619040cc287"), make: "Audi", model: "A1", year: [2017, 2019, 2020] }

It’s important to note that if the mentioned field is absent in the document to update, the $push operator adds this field to the document as an array and includes the given value as its element.

For example, consider our document from the automobiles collection again. Let’s say we wanted to update the country that manufactures this make of vehicle using the following command:

db.vehicles.updateOne( { make: "Audi" }, { $push: { country: "Germany" }} );

Because our document did not previously have a field called country, running this command would add the new field to the document as an array and insert one element, the string "Germany". Our output would look as follows:

{ _id: ObjectId("627934bbfd6a8619040cc287"), make: "Audi", model: "A1", year: [2017, 2019], country: "Germany" }

Let’s practice updating array fields with the $push operator with documents in our restaurants database!

Instructions

1.

Connect to the restaurants database. Then, using the .findOne() method on the listingsAndReviews collection, find the document with the field name with the value of "Cafe Bar". Observe the properties of the document!

2.

Cafe Bar recently got examined again and received a new grade. Insert a new element into the grades array with the following properties:

date: new Date(), grade: "B", score: 81
3.

Print out the same document using the name of the restaurant in order to see the updated values.

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?