Try Studio 3T for Free
  1. Knowledge Base
  2. MongoDB Tutorials
  3. MongoDB find() Method: Introduction & Examples

MongoDB find() Method: Introduction & Examples

In this article, we’ll go through the basics of  find(), the method used to fetch a document from a MongoDB collection.

Follow along this introduction by downloading Customers, an entirely faked list of customers, here, and importing it into your database.

Find() method parameters

The find() method has two parameters:

 db.collection.find(<query>,<projection>)
  • the first ‘query‘ or filter parameter specifies the search
  • the second optional ‘projection’ parameter specifies what parts of each matching document are returned

Find() method examples

For writing and building db.collection.find() queries, I like to use either Studio 3T’s SQL Query window, which lets you use SQL to query MongoDB. SQL Query saves a bit of typing if you are fluent in SQL.

Studio 3T's SQL Query feature lets you use SQL to query MongoDBIf you are comfortable with the mongo shell, there’s Studio 3T’s IntelliShell with query auto-completion.

You can use the MongoDB find method in Studio 3T's IntelliShell, the built-in mongo shell that autocompletes queries down to field names

Try SQL Query and IntelliShell by downloading the latest Studio 3T version here.

Using IntelliShell and the Customers collection (download it here), here are some examples of the find() method that you can try out and change, so as to see what happens.

Return all documents in a collection

db.Customers.find()

//returns all documents in the collection

When the query and projection parameters are not specified, the find() method returns all documents in the collection.

Return documents that match the given query criteria

db.Customers.find({
   'Addresses.County': 'Norfolk'
})

//returns the documents that have an address in the county of Norfolk

This query simply returns the documents that contain an address in the county of Norfolk. There is a filter parameter but no projection is specified so the whole document with all the fields is returned.

Return documents with only the specified fields (projection)

Here we have specified a list of the fields that we want returned as the projection parameter.

db.Customers.find({
   'Addresses.County': 'Norfolk'
}, {
   '_id': 0,
   'Full Name': 1,
   'Addresses.$': 1
})

The customer may use several addresses at once (work, home, etc.), and he may move about, so we have chosen to just return the matching address (‘Addresses.$’), along with the name of the customer (‘Full Name’). For this query, that is all the data we need, so why retrieve more than necessary?

The projection parameter allows you to specify whether a list of fields or arrays is, or is not, returned.

If you are providing an inclusive list of the data to be returned, you are only allowed to exclude the _id field.

Return documents with multiple matching criteria

What if you want to search in more than one county?

db.Customers.find({
  'Addresses.County': {
    $in: ['Essex', 'Suffolk', 'Norfolk', 'Cambridgeshire']
  }
})

//customers whose address is in East Anglia

The filter allows more than simple equality with a value to select documents. In this case we’ve listed several values to check for using the $in comparison query operator.

There are several others with fairly obvious meanings, such as $eq (==), $gt (>), $lt (<), $gte (>=), $lte (<=), $ne (!=) and $nin (not in).

There are also the range of logical operators. There are plenty of other MongoDB query and projection operators that allow you to do quite complex filters, but that’s another topic!

Using the cursor methods

The MongoDB find method doesn’t actually return the data despite the fact that, by default, the mongo shell prints out the first twenty rows when it executes the find() method.

It is a cursor to the documents that gets passed back. It holds a reference to the documents that match the query criteria that you pass to the find() method. This allows you to specify what processing you want on the returned data.

There are a number of these cursor methods.

count()

The count() cursor method is useful for returning the number of documents that meet the criteria.

For example, in our customer database:

db.Customers.find({'Addresses.County': 'Norfolk'}).count()

shows how many customers have an address in Norfolk County.

limit()

The limit() cursor method limits the number in the result to the value you pass, so that

db.Customers.find({'Addresses.County': 'Norfolk'}).limit(1)

returns just the first customer.

skip()

There is also a skip() method so you can easily implement a scrolling window in the application.

db.Customers.find({
  'Addresses.County': 'Norfolk'
}, {
  '_id': 0,
  'Full Name': 1
}).sort({
  'Name.Last Name': 1
}).skip(10).limit(20)

As you’ll have noticed, you can stack these methods up and use pretty()

db.Customers.find({'Addresses.County': 'Norfolk'}).limit(1).pretty()

to return the document in an easy-to-read format.

The skip() and limit() methods make little sense without the sort() method because results are best assumed to be unordered otherwise.

The toArray() method is powerful magic, because it creates a JSON array from all the documents specified by the cursor. It is the easiest way to pass results to the application.

Next, learn how to use the find() method – along with indexes – to spot slow-performing queries.

Updated on February 17, 2020

Was this article helpful?

Related Articles

Leave a Comment