Great job! We’ve covered numerous topics regarding creating and updating documents in collections. Let’s recap some key takeaways from this lesson:
_idfield is a unique identifier for documents in a collection. By default, MongoDB assigns an
ObjectIdvalue to the
_idfield for each document.
- Individual documents can be added to a collection with
.insertOne(), and the document to be inserted is provided as an argument.
- Multiple documents can be inserted into a collection with the
.insertMany()method. An array containing all the documents to insert is passed in an argument.
.updateOne()method is used to update the first document within the collection that matches a given query.
- We can use
.updateMany()to update multiple matching documents simultaneously.
$pushoperator appends a specified value to an array.
.findAndModify()method modifies and returns a single document in a collection. By default, it returns the original document, and if no matching document is found, a new one can be inserted by adding the upsert option.
In addition to the methods we’ve learned throughout this lesson, MongoDB offers us other syntax and commands that can be useful when inserting, updating, or replacing documents:
orderedparameter can be provided to the
.insertMany()method. It accepts a boolean value, and, if set to false, will insert the documents in an unordered format to increase performance.
$unsetoperator can be provided to the
.updateMany()method. It removes a particular field from a document.
.findOneAndUpdate()method is similar to
.updateOne(), but instead of returning a document acknowledging the success or failure of our operation, it returns either the original or updated document.
.renameCollection()method allows us to update the name of our collection without modifying any of its documents.
.bulkWrite()method allows us to perform multiple write operations (updating or inserting) with controls for order of execution.
There are many different implementations of inserting or modifying data in MongoDB, so make sure to explore the docs for more examples!
We have provided you with the
listingsAndReviews collection. Before moving on, spend some time experimenting with writing queries using the syntax you learned throughout this lesson. If you are up for a challenge, try any of the following tasks listed below. Remember to first connect to the
restaurants database to access the
listingsAndReviews collection. Good luck, and click Up Next when you are ready to move on!
- Rename the
listingsAndReviewscollection to a name of your choice.
- Update all the restaurants from your favorite NYC borough by removing the
gradesfield. They are all a
'A'in your eyes!
.bulkWrite()to perform the following operations in any order:
- Add three documents using insertOne.
- Update two documents using updateMany.
- Replaces a document using replaceOne.