By this point, we’ve learned the fundamentals of querying data in MongoDB. In this lesson, we’ll learn how to insert new documents, and update existing ones.
As you continue to work with documents in MongoDB, you may notice one field that exists across every document: the
_id field. It might look similar to this:
_id field plays a vital role in every document inside of a MongoDB collection, and it has a few distinct characteristics:
_idfield is required for every document in a collection and must be unique.
- MongoDB automatically generates an
_idfield if no value is provided.
- Developers can specify the
_idwith something other than an
ObjectIdsuch as a number or random string, if desired.
_idfield is immutable, and once a document has an assigned
_id, it cannot be updated or changed.
ObjectId is a 12-byte data type that is commonly used for the
_id field. When generated automatically, each
ObjectId contains an embedded timestamp which is generally unique. This allows documents to be inserted in order of creation time (or very close to it) and for users to roughly sort their results by creation time if necessary. While we won’t explicitly need the _id field to update or create new documents, it’s important to note that this is how MongoDB identifies each unique document that is inserted or updated in a collection.
Let’s return to our
restaurants collection to look at the
_id fields that currently exist in our documents.
Connect to the
restaurants database, then using the
listingsAndReviews collection, query for all the documents in the collection using the
.find() method. Take a moment to observe the
_id field in each document.