findOne and the _id Field
A movies collection is ready for you in this course. It holds eight movies, one document for each. findOne() gets one document from a collection. With nothing inside the parentheses, it gives you the first document:
db.movies.findOne()
Output:
{
_id: 1,
title: 'Inception',
director: 'Christopher Nolan',
year: 2010,
rating: 8.8,
votes: 2400,
genres: [ 'sci-fi', 'thriller' ]
}
This is the same kind of document you saw in the first lesson. It has numbers, text, an array, and the _id field at the top. mongosh shows text in single quotes, like 'Inception'. In JavaScript, single and double quotes mean the same thing.
To get a particular document, give findOne a filter. A filter is a small document that describes what you are looking for. { _id: 2 } means "the document whose _id is 2":
db.movies.findOne({ _id: 2 })
Output:
{
_id: 2,
title: 'Interstellar',
director: 'Christopher Nolan',
year: 2014,
rating: 8.7,
votes: 2100,
genres: [ 'sci-fi', 'drama' ]
}
In this course, every movie has a small number as its _id. We picked these numbers when we loaded the data. If you add a document without an _id, MongoDB makes one for you. You will see this in the lesson on inserting.
In the exercise, get the movie whose _id is 3.