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: ObjectId("5eb3d668b31de5d588f4305b")
The _id
field plays a vital role in every document inside of a MongoDB collection, and it has a few distinct characteristics:
- The
_id
field is required for every document in a collection and must be unique. - MongoDB automatically generates an
ObjectId
for the_id
field if no value is provided. - Developers can specify the
_id
with something other than anObjectId
such as a number or random string, if desired. - The
_id
field is immutable, and once a document has an assigned_id
, it cannot be updated or changed.
The 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.
Instructions
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.