Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 70 ยท CRUD: create and read

Finding Documents

Learn how MongoDB find and findOne work: filter documents, equality matching on several fields, the empty filter, matching array fields and how cursors behave.

Reading data is the job you will do most. In MongoDB you read with find, which takes a filter document describing the documents you want and returns a cursor to the matches. If you only need one document, findOne returns it directly.

This lesson stays with the simplest filters: matching fields by equality. Operators such as $gt and $in come later, starting with Comparison Operators. First you need to understand the shape of a query, what "equal" means, and what a cursor is, because the cursor trips up almost every beginner.

The mongosh listings are real MongoDB commands and are read-only. The runnable examples use the JavaScript practice engine from The Practice Engine Used in This Tutorial. It imitates find, findOne and cursors over an array of documents. It is a stand-in for learning the behavior, not a database.

Anatomy of a query

Filter A document that says what to match.
Projection Optional list of fields to return.
Cursor A handle on the results, not the results.
1 / 2

The filter document

A filter is itself a document. Each field in it is a condition, and a document matches when it satisfies all of them. Imagine a books collection:

JavaScript
db.books.find({ genre: "fantasy" })

This returns every document whose genre field equals "fantasy". Two conditions are combined with a logical AND:

JavaScript
db.books.find({ genre: "fantasy", year: 2019 })

Only books that are fantasy and from 2019 come back. The same filter works for findOne, which returns the first match in the collection's natural order, or null when nothing matches:

JavaScript
db.books.findOne({ title: "The Glass Orchard" })

If you do not care which document you get, because for example you want to peek at the structure of a collection, call findOne() with no arguments.

The empty filter

An empty filter {} has no conditions, so every document satisfies it. db.books.find({}) and db.books.find() both return the whole collection. That is fine for a tiny collection and a bad habit on a big one, so you will soon add limits and projections (see Projection: Choosing Fields and Sorting, Limiting and Skipping).

What "equal" means

Equality in MongoDB is strict about three things:

  • Type matters. { year: 2019 } matches the number 2019 but not the string "2019". A collection that has mixed types for the same field will return surprising results.
  • Case matters. { genre: "fantasy" } does not match "Fantasy". For case-insensitive matching you need a regular expression or a collation, covered in Text Matching and Regular Expressions.
  • Missing equals null. A filter { publisher: null } matches documents where publisher is null and documents that do not have a publisher field at all.

When the field holds an array, an equality condition matches if the array contains the value. A book with tags: ["magic", "orchard"] matches { tags: "magic" }. If the filter value is itself an array, MongoDB compares the whole array, in order. Arrays and nested documents get a full lesson in Querying Nested Fields and Arrays.

The first TryIt runs these rules against a small collection. Change the filters and check the results before you read the next section.

JS Equality filters

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at the publisher: null line. It returns three books: the one whose publisher is explicitly null and the two that have no publisher field at all. If you want only documents where the field exists with a null value, you need $type or $exists, which Element and Evaluation Operators explains.

Cursors

find does not return an array. It returns a cursor: an object that remembers your query and fetches matching documents from the server in batches as you ask for them. This keeps memory use low when a query matches millions of documents, because the first batch arrives right away and the rest are fetched on demand.

In mongosh, if you do not store the cursor, the shell iterates it for you and prints the first 20 documents. Type it to see the next 20. In an application you consume the cursor yourself:

  • toArray() reads everything that is left into an array. Fine for small results, dangerous for huge ones.
  • A loop, such as for await (const doc of cursor) in the Node.js driver or for doc in cursor in PyMongo, processes one document at a time.
  • next() and hasNext() give you manual control.

Cursors are single-use. Once you have read the documents, they are gone from the cursor: calling toArray() a second time on the same cursor returns an empty array. To read the data again, run the query again. Cursors also expire on the server after a period of inactivity (ten minutes by default), so do not hold one open while you do slow work between reads.

Counting is separate from reading. db.books.countDocuments({ genre: "fantasy" }) returns how many documents match. For an estimate of the whole collection's size without a filter, estimatedDocumentCount() is much cheaper. Use countDocuments when you need an exact count for a filter.

JS A cursor is read once

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Things to remember about find

  • Query results are not guaranteed to come back in any particular order unless you sort them. In practice you often see insertion order on a simple collection, but that is not a promise. See Sorting, Limiting and Skipping.
  • Field names in a filter are case sensitive and a typo does not raise an error; it simply matches nothing.
  • Reading never changes the data. find and findOne are safe to experiment with.
  • Use findOne when you expect one document, for example by _id. It makes your intent clear and the server can stop looking after the first match.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does db.books.find({ genre: 'fantasy', year: 2019 }) return?

    Several fields in one filter are combined with AND. The OR case needs the $or operator, covered in Logical Operators.
  2. 2. A collection stores year as the number 2019 in some documents and the string '2019' in others. What does { year: 2019 } match?

    Equality is type strict. The string and the number are different values, so only the number matches.
  3. 3. You run cur = db.books.find(); cur.toArray(); and then cur.toArray() again. What does the second call return?

    A cursor is consumed as you read it. To get the documents again, run the query again.
  4. 4. Which filter matches documents where publisher is null or the publisher field is missing?

    Equality with null matches both an explicit null and an absent field. $exists: true would match only documents that have the field.

Summary

  • find(filter) returns a cursor over all matching documents; findOne(filter) returns one document or null.
  • A filter lists field conditions that must all be true; the empty filter {} matches everything.
  • Equality is strict about type and case, null also matches a missing field, and an array field matches when it contains the value.
  • A cursor fetches documents lazily in batches and can be read only once; use toArray(), a loop, or next().
  • Use countDocuments(filter) for an exact count and add sorting, limits and projections before reading large collections.

Next, choose which fields to return with Projection: Choosing Fields.