CodeStride
Getting Started

Finding documents in NoSQL

Topic 3 of 34 · 9 minFree lesson

findOne gives you one document. Most of the time you want every document that matches, like all the books by one author. That's what find does.

Finding every document

find() with nothing in the brackets returns every document in the collection. The shell shows them as a list.

Example 1
db.authors.find()
[ { _id: 'austen', name: 'Jane Austen', born: 1775, country: 'United Kingdom' }, { _id: 'butler', name: 'Octavia E. Butler', born: 1947, country: 'United States' }, { _id: 'achebe', name: 'Chinua Achebe', born: 1930, country: 'Nigeria' }, { _id: 'leguin', name: 'Ursula K. Le Guin', born: 1929, country: 'United States' }, { _id: 'murakami', name: 'Haruki Murakami', born: 1949, country: 'Japan' }, { _id: 'adichie', name: 'Chimamanda Ngozi Adichie', born: 1977, country: 'Nigeria' }]

Finding the documents that match

Put a filter in the brackets: a document that describes what you're looking for. find returns every document whose fields match it.

Example 2
db.books.find({ author: "Jane Austen" })
[ { _id: 2, title: 'Emma', author: 'Jane Austen', year: 1815, genres: [ 'romance', 'classic' ], price: 7, stock: 0, ratings: { average: 4.1, count: 180 } }, { _id: 7, title: 'Pride and Prejudice', author: 'Jane Austen', year: 1813, genres: [ 'romance', 'classic' ], price: 6.5, stock: 9, ratings: { average: 4.4, count: 350 } }]

findOne would stop at the first match. find gives you both books.

Matching several fields

A filter can name several fields. A document must match all of them to come back. Here, only books from 1987 that cost 11 match.

Example 3
db.books.find({ year: 1987, price: 11 })
[ { _id: 3, title: 'Beloved', author: 'Toni Morrison', year: 1987, genres: [ 'literary' ], price: 11, stock: 5, ratings: { average: 4.3, count: 210 } }]

Two books are from 1987, but only Beloved costs 11.

When nothing matches

If no document matches, find returns nothing at all, so the shell shows nothing. There's no error.

Example 4
db.books.find({ author: "Agatha Christie" })

Counting what matches

countDocuments takes a filter too. It's a quick way to check how many documents match before you look at them.

Example 5
db.orders.countDocuments({ status: "pending" })
2
Common mistakePutting a number in quotes. In quotes, "1965" is a string, and the year field holds the number 1965. A string never equals a number, so nothing matches and the shell shows nothing.
Example 6
db.books.find({ year: "1965" })

Write numbers without quotes: { year: 1965 }.

TipUse findOne when you expect one document, like a book by its _id. Use find when there could be many.

Try it yourself

Run the code in the editor and answer 8 practice questions on finding documents. It's free, you only need an account.