Skip to content
Studio 3T - The professional GUI, IDE and client for MongoDB
  • Tools
    • Aggregation Editor
    • IntelliShell
    • Visual Query Builder
    • Export Wizard
    • Import Wizard
    • Query Code
    • SQL Query
    • Connect
    • Schema Explorer
    • Compare
    • SQL ⇔ MongoDB Migration
    • Data Masking
    • Task Scheduler
    • Reschema
    • More Tools and Features
  • Solutions
  • Resources
    • Knowledge Base
    • MongoDB Tutorials & Courses
    • Tool/Feature Documentation
    • Blog
    • Community
    • Testimonials
    • Whitepapers
    • Reports
  • Contact us
    • Contact
    • Sales Support
    • Feedback and Support
    • Careers
    • About Us
  • Store
    • Buy Now
    • Preferred Resellers
    • Team Pricing
  • Download
  • My 3T
search

Studio 3T® Knowledge Base

  • Documentation
  • Tutorials
  • Workshops
Take the fastest route to learning MongoDB. Cover the basics in two hours with MongoDB 101, no registration required.
Start the free course

MongoDB find Method: Introduction & Examples

Posted on: 17/02/2020 (last updated: 04/08/2021) by Phil Factor

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

We’ll go through a few query examples using Studio 3T and the Customers dataset, which is an entirely faked list of customers.

What is MongoDB find?

The find() method in MongoDB selects documents in a collection or view and returns a cursor to the selected documents. It has two parameters: query and projection.

 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

Three ways to build find() queries in Studio 3T

For writing and building db.collection.find() queries, we’ll be using Studio 3T’s IntelliShell with query auto-completion in our examples.

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

If you don’t know the MongoDB Query Language, you can still build find() queries through a drag-and-drop Visual Query Builder. Simply drag the fields, define the value,  and hit Run.

If you’re fluent in SQL and want to save a bit of typing, Studio 3T also has SQL Query, which lets you use SQL to query MongoDB.

Studio 3T's SQL Query feature lets you use SQL to build MongoDB find queries

Try  IntelliShell, Visual Query Builder, and SQL Query by downloading the latest Studio 3T version.

Import the Customers collection

We’ll be querying the Customers collection, available here as a .json file download. If you have an existing collection, skip ahead to the examples.

Open Studio 3T and connect to your MongoDB database.

Next, open the Import Wizard from the toolbar.

Click on Import from the Global Toolbar

Then, choose JSON as the import format.

Choose JSON as the import format

Click OK.

Click on + to add JSON source documents, – to remove them, or the clipboard icon to paste JSON data from the clipboard.

Here we will add our JSON source document, Customers.

Double-click on a cell to type in the target collection. We are naming ours Customers. Note the capital C!

Insertion mode in JSON import

Under the Insertion Mode column, double-click on a cell to choose one of the insertion modes from the drop-down menu.

Click on Execute to run the import. You should see the new collection in the connection tree, on the left.

Choose Save task, Save task as, or Execute from the Import Wizard toolbar

Find() method examples

Now we’re ready to try out examples of the find() method that you can type/paste and edit in IntelliShell.

Let’s open IntellIShell by clicking the icon in the toolbar.

Click on IntelliShell on the toolbar

And try the following queries.

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.

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.

MongoDB find() exercises

Follow step-by-step exercises on how to run find statements on Academy 3T, home of our free MongoDB 101 and MongoDB 201 courses. The lesson on the The MongoDB find method has you covered.


How helpful was this article?
This article was hideous
This article was bad
This article was ok
This article was good
This article was great
Thank you for your feedback!

About The Author

Phil Factor

Phil Factor (real name withheld to protect the guilty), aka Database Mole, has 30 years of experience with database-intensive applications. Despite having once been shouted at by a furious Bill Gates at an exhibition in the early 1980s, he has remained resolutely anonymous throughout his career.

Article navigation

Related articles

  • Lesson 2: The MongoDB find method
  • How MongoDB Indexes Work (With Examples)
  • Lesson 3: Introducing the MongoDB aggregate method
  • Getting Started with MongoDB – An Introduction
  • Test your skills: Introduction to MongoDB and Studio 3T

Studio 3T

MongoDB Enterprise Certified Technology PartnerSince 2014, 3T has been helping thousands of MongoDB developers and administrators with their everyday jobs by providing the finest MongoDB tools on the market. We guarantee the best compatibility with current and legacy releases of MongoDB, continue to deliver new features with every new software release, and provide high quality support.

Find us on FacebookFind us on TwitterFind us on YouTubeFind us on LinkedIn

Education

  • Free MongoDB Tutorials
  • Connect to MongoDB
  • Connect to MongoDB Atlas
  • Import Data to MongoDB
  • Export MongoDB Data
  • Build Aggregation Queries
  • Query MongoDB with SQL
  • Migrate from SQL to MongoDB

Resources

  • Feedback and Support
  • Sales Support
  • Knowledge Base
  • FAQ
  • Reports
  • White Papers
  • Testimonials
  • Discounts

Company

  • About Us
  • Blog
  • Careers
  • Legal
  • Press
  • Privacy Policy
  • EULA

© 2023 3T Software Labs Ltd. All rights reserved.

  • Privacy Policy
  • Cookie settings
  • Impressum

We value your privacy

With your consent, we and third-party providers use cookies and similar technologies on our website to analyse your use of our site for market research or advertising purposes ("analytics and marketing") and to provide you with additional functions (“functional”). This may result in the creation of pseudonymous usage profiles and the transfer of personal data to third countries, including the USA, which may have no adequate level of protection for the processing of personal data.

By clicking “Accept all”, you consent to the storage of cookies and the processing of personal data for these purposes, including any transfers to third countries. By clicking on “Decline all”, you do not give your consent and we will only store cookies that are necessary for our website. You can customize the cookies we store on your device or change your selection at any time - thus also revoking your consent with effect for the future - under “Manage Cookies”, or “Cookie Settings” at the bottom of the page. You can find further information in our Privacy Policy.
Accept all
Decline all
Manage cookies
✕

Privacy Preference Center

With your consent, we and third-party providers use cookies and similar technologies on our website to analyse your use of our site for market research or advertising purposes ("analytics and marketing") and to provide you with additional functions (“functional”). This may result in the creation of pseudonymous usage profiles and the transfer of personal data to third countries, including the USA, which may have no adequate level of protection for the processing of personal data. Please choose for which purposes you wish to give us your consent and store your preferences by clicking on “Accept selected”. You can find further information in our Privacy Policy.

Accept all cookies

Manage consent preferences

Essential cookies are strictly necessary to provide an online service such as our website or a service on our website which you have requested. The website or service will not work without them.

Performance cookies allow us to collect information such as number of visits and sources of traffic. This information is used in aggregate form to help us understand how our websites are being used, allowing us to improve both our website’s performance and your experience.

Google Analytics

Google Ads

Bing Ads

Facebook

LinkedIn

Quora

Hotjar

Reddit

Functional cookies collect information about your preferences and choices and make using the website a lot easier and more relevant. Without these cookies, some of the site functionality may not work as intended.

HubSpot

Social media cookies are cookies used to share user behaviour information with a third-party social media platform. They may consequently effect how social media sites present you with information in the future.

Accept selected