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

Academy 3T

  • Explore our courses
    • MongoDB 101: Getting Started
    • MongoDB 201: Querying MongoDB Data
    • MongoDB 301: Aggregation
  • Get certified

Lesson 2: The MongoDB find method

MongoDB 201: Querying MongoDB Data Building MongoDB find() Queries Lesson 2: The MongoDB find method

The MongoDB find method provides the foundation for performing basic queries against a MongoDB database.

The following syntax shows the elements you must include when calling the find method, along with several optional elements, which are enclosed in brackets:

db.collection.find([{query}] [,{projection}])[.method];

To invoke the find method, you start by specifying the db object, which points to the currently active database.

You then provide the target collection, replacing the collection placeholder with the collection’s name.

In most cases, you can specify the name without using any special constructs, although there are some exceptions to this, which will be discussed shortly.

After you specify the collection, you then call the find method.

MongoDB find method arguments

The method takes two arguments: the query and the projection, both of which are optional.

If you don’t specify either argument, the method returns all documents in the current collection and includes all their fields.

For example, the following MongoDB find statement returns all documents in the customers collection in their entirety:

db.customers.find();

A find statement must always run within the context of the database where the collection is stored.

If you open IntelliShell from a database node on the Connection Tree, the find statement automatically runs within the context of that database.

For example, if you launch IntelliShell from the sales database node, any find statements you run will do so within the context of the sales database.

If you want to run a find statement against a database other than the currently active one, you must first set the context to the new database by running a use statement.

For example, the following use statement sets the context to the sales database:

use sales;

After you run this statement, all find statements will execute within the context of the sales database until you change the context to a different database.

In some cases, you might also need to use the getCollection method to specify the collection name if the name could cause confusion with the MongoDB engine.

For example, if the database name begins with a special character such as an underscore or is the same as a mongo shell keyword, you’ll need to use the getCollection method.

You can use the getCollection method for specifying any collection. For example, the following find statement returns the same results as the first example, but uses the getCollection method to specify the collection:

db.getCollection("customers").find({});

Notice that the find method in this example includes curly braces within the method’s parentheses. The braces represent a query argument that includes no search conditions, in which case, all documents are returned. 

Whether you include or exclude the braces, the results are the same. However, if you want to limit your results to specific documents, you must include one or more search conditions in your query argument. 

Each search condition focuses on a specific document element within the collection, serving as a filter that determines which documents to include in the results.

Adding search conditions to the query argument

For example, the query argument in the following find statement contains two search conditions, one specific to the package field and the other specific to the registered_on field:

db.customers.find(
  {
    "package":"Free",
    "registered_on":{$gt:new Date("1989-12-31")}
  } 
);

Notice that the two search conditions are enclosed in curly braces and separated by a comma.

The first search condition specifies that a document’s package field value must equal Free. The second search condition specifies that a document’s registered_on data value must come after 1989-12-31. 

The second search condition uses the $gt (greater than) operator to provide the comparison logic necessary to determine whether to include a document in the results. The value used for comparison is a string that must be converted to a Date object before it can be compared to the registered_on values.

Both search conditions must evaluate to true for a document to be returned. The following figure shows part of the results returned by the find statement after running it in IntelliShell.

Full set of results

Adding the projection argument

If you want to limit the results to certain fields, you can add a projection argument that specifies the field names.

The projection argument is added after the query argument, with the two separated by a comma.

Like the query argument, the projection argument is also enclosed in curly braces. For example, the following find statement includes a projection argument specifying that results should include the first, last, and email fields:

db.customers.find(
  {
    "package":"Free",
    "registered_on":{$gt:new Date("1989-12-31")}
  },
  { first: 1, last: 1, email: 1}
);

When you specify the field names, you must separate them with a comma and provide a value of either 1 or 0. A value of 1 indicates that the field should be included, and a value of 0 indicates that it should not. 

You cannot mix and match fields in the projection argument. They must all be included fields (1) or all excluded fields (0). The only exception to this is the _id field, which can be excluded even if all other fields are included.

The reason for this is that the _id field is included with your query results by default. For example, the find statement above returns the document fields shown in the following figure. 

find query tab

The results include the _id field, even though it’s not specified in the projection. However, you can exclude the field by adding it to the projection and setting its value to 0.

The MongoDB find method can also be used with other methods to help refine your searches even further, such as being able to sort them or limit the number of returned documents.

For example, the following find statement users the sort method to order the results by the last field.

db.customers.find(
  {
    "package":"Free",
    "registered_on":{$gt:new Date("1989-12-31")}
  },
  { first: 1, last: 1, email: 1}
).sort({last:1});

When specifying the sort fields, you can also specify the sort order, using 1 for ascending (the default) and -1 for descending. The find statement in this example returns the results shown in the following figure.

find query

As noted above, Studio 3T provides several tools for querying data. Two of these tools are IntelliShell and Visual Query Builder, which can be particularly useful for understanding how the MongoDB find method works.

In the exercises to follow, you’ll use both tools to create and run several find statements in order to better understand the basics of querying MongoDB data.

Previous Lesson
Back to Lesson
Next Topic
  • Course Home Expand All
    Performing MongoDB CRUD Operations
    4 Topics | 1 Quiz
    Lesson 1, Exercise 1: Adding a document to a collection
    Lesson 1, Exercise 2: Viewing a document in a collection
    Lesson 1, Exercise 3: Updating a document in a collection
    Lesson 1, Exercise 4: Deleting a document from a collection
    Test your skills: Performing CRUD Operations
    Building MongoDB find() Queries
    4 Topics | 1 Quiz
    Lesson 2: The MongoDB find method
    Lesson 2, Exercise 1: Using IntelliShell to build and run find statements
    Lesson 2, Exercise 2: Using Visual Query Builder to build and run find statements
    Lesson 2, Exercise 3: Using Query Code and IntelliShell to modify and run a find statement
    Test your skills: Building MongoDB find() Queries
    Working with the MongoDB Aggregation Pipeline
    6 Topics | 1 Quiz
    Lesson 3: Introducing the MongoDB aggregate method
    Lesson 3, Exercise 1: Filtering the documents in the aggregation pipeline
    Lesson 3, Exercise 2: Grouping the documents in the aggregation pipeline
    Lesson 3, Exercise 3: Adding and removing fields in the aggregation pipeline
    Lesson 3, Exercise 4: Changing the field order in the aggregation pipeline
    Lesson 3, Exercise 5: Sorting the documents in the aggregation pipeline
    Test your skills: Working with the MongoDB Aggregation Pipeline
    Querying Arrays Using MongoDB $elemMatch
    4 Topics | 1 Quiz
    Lesson 4, Exercise 1: Using IntelliShell to query single and multiple values in an array
    Lesson 4, Exercise 2: Using Visual Query Builder to query a single array value
    Lesson 4, Exercise 3: Using Visual Query Builder to query multiple array values
    Test your skills: Querying Arrays Using MongoDB $elemMatch
    MongoDB 201 Mid-Course Feedback
    Querying Embedded Documents in MongoDB Arrays
    3 Topics | 1 Quiz
    Lesson 5, Exercise 1: Using the $elemMatch operator to query embedded documents
    Lesson 5, Exercise 2: Using conditional operators to query embedded documents
    Lesson 5, Exercise 3: Using Visual Query Builder to query embedded documents
    Test your skills: Querying Embedded Documents in Arrays
    Querying MongoDB with SQL SELECT Statements
    2 Topics | 1 Quiz
    Lesson 6, Exercise 1: Using the SQL Query tool to run SQL statements
    Lesson 6, Exercise 2: Using the SQL Query tool to aggregate collection data
    Test your skills: Querying MongoDB with SQL
    Working with MongoDB Views
    3 Topics | 1 Quiz
    Lesson 7, Exercise 1: Creating a MongoDB view
    Lesson 7, Exercise 2: Querying a MongoDB view
    Lesson 7, Exercise 3: Modifying and deleting a MongoDB view
    Test your skills: Working with MongoDB Views
    Course Extras
    Return to MongoDB 201: Querying MongoDB Data
  • 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

    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