find: Querying With Documents
find() returns every document that matches a filter. findOne stops at the first match, but find keeps going. Like findOne, it takes a filter document:
db.movies.find({ year: 2014 })
Output:
[
{
_id: 2,
title: 'Interstellar',
director: 'Christopher Nolan',
year: 2014,
rating: 8.7,
votes: 2100,
genres: [ 'sci-fi', 'drama' ]
},
{
_id: 4,
title: 'Whiplash',
director: 'Damien Chazelle',
year: 2014,
rating: 8.5,
votes: 1500,
genres: [ 'drama', 'music' ]
}
]
{ year: 2014 } means "the year field is equal to 2014". Two movies match.
find does not return the documents themselves. It returns a cursor, an object that points to the matching documents. The shell reads the cursor for you and shows the documents in square brackets, even when only one document matches.
A cursor looks like an array, but it is not one. Array features such as .length do not work on it. When you need a real array, add .toArray():
db.movies.find({ year: 2014 }).toArray().length
Output:
2
You will not need .toArray() in this course, because the shell shows the results of a cursor by itself.
Text works the same way. Put the text in quotes:
db.movies.find({ director: "Bong Joon-ho" })
Output:
[
{
_id: 3,
title: 'Parasite',
director: 'Bong Joon-ho',
year: 2019,
rating: 8.5,
votes: 1800,
genres: [ 'thriller', 'drama' ]
},
{
_id: 6,
title: 'Okja',
director: 'Bong Joon-ho',
year: 2017,
rating: 7.8,
votes: 900,
genres: [ 'drama' ]
}
]
Text must match exactly, and capital letters matter. "bong joon-ho" does not match "Bong Joon-ho". When no document matches, there is no error. The shell just shows nothing.
An empty filter {} matches every document. So does find() with nothing inside the parentheses.
A filter like this can only check that a field is equal to a value. For questions like "after 2015" or "rated above 8", you need operators. You will learn them two lessons from now. The next lesson shows how to get back only the fields you need.
In the exercise, find every movie directed by Christopher Nolan.