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, Exercise 1: Using IntelliShell to build and run find statements

MongoDB 201: Querying MongoDB Data Building MongoDB find() Queries Lesson 2, Exercise 1: Using IntelliShell to build and run find statements

In this exercise, you’ll use IntelliShell to create and run several find statements that retrieve data from the customers collection.

The exercises in this section are based on the sales database and the customers collection. The first section in MongoDB 201 demonstrated how to create the database and import the collection. Refer to that section for details on how to set them up if you haven’t done so already.

To build and run the find statements

1. Launch Studio 3T and connect to MongoDB Atlas.

Don’t have a MongoDB Atlas instance? Here’s how to set up a free cluster, or connect to an existing MongoDB database or localhost instead.

2. In the Connection Tree, right-click the sales database node and click Open IntelliShell. Studio 3T opens IntelliShell in its own tab in the main window.

3. On the IntelliShell toolbar, make sure Query Assist is enabled. This will make it easier to view the results returned by the mongo shell commands. Let’s also turn on auto-completion by clicking on the lightning bolt icon.

IntelliShell with auto-completion and Enable Query Assist on

Query Assist is enabled by default in IntelliShell. It adds functionalities that are not available for shell-run queries like code generation, visual explain plans, and editable result tabs. Learn more about it in the Introducing IntelliShell lesson.

4. At the command prompt in the IntelliShell editor, type or paste the following command:

db.customers.find();

The command returns all data in the customers collection. The collection includes 1,000 documents, each one a customer record.

5. On the IntelliShell toolbar, click the Run entire script button (Execute entire script).

Studio 3T runs the find statement and returns the results in the bottom window, displaying them in the Find tab. The tab is similar to the Result tab on a collection tab. For example, you can display the results in different views and work with the document data directly.

find-query return 1000 documents

6. The next query you’ll create will limit the results to those documents whose device field value is Apple iPhone.

At the command prompt, delete the current statement and then type or paste the following command:

db.customers.find({"device":"Apple iPhone"});

The find method includes a query argument with a single search condition. The search condition species that the device field value must equal Apple iPhone in order for a document to be returned. Notice that the search condition is enclosed in curly braces, with a colon separating the field name from its value.

7. On the IntelliShell toolbar, click the Run entire script button. The results should now include 537 documents.

Find query to filter Apple iPhone as device

Are you getting 538 documents? Don’t forget – we deleted the document whose last field value is Grey in a previous exercise.

8. Next, you’ll create a query that limits the results to those documents whose address.state field value is either Washington or Oregon. At the command prompt, delete the current statement and then type or paste the following command:

db.customers.find(
  {"address.state":{$in:["Washington", "Oregon"]}}
);

As with the previous example, the query argument includes only one search condition.

In this case, however, the search condition uses the $in operator to specify the field’s acceptable values (Washington and Oregon). Now only documents that include either of these values will be returned.

9. On the IntelliShell toolbar, click the Run entire script button. The results should now include only 29 documents—those whose address.state field value is either Washington or Oregon.

With additional state filters: Washington and Oregon

10. You’ll now combine the search conditions defined in the previous two examples, only this time you’ll specify that the device field can include any value that contains the term iphone.

At the command prompt, delete the current statement and then type or paste the following command:

db.customers.find(
  {
    "address.state":{$in:["Washington", "Oregon"]},
    "device":/.*iphone.*/i
  } 
);

The first search condition specifies the permitted address.state values, and the second search condition specifies the permitted device values. You must separate the search conditions with a comma.

The value in the second search condition (/.*iphone.*/i) is a regular expression that’s used for pattern matching.

  • The forward slashes enclose the regular expression.
  • The trailing i specifies that the search condition is case-insensitive.
  • The two period/asterisk (.*) pairs indicate that zero or more characters can proceed or follow the term iphone.

As a result, the term can appear anywhere in the field’s value and still be included in the search results.

11. On the IntelliShell toolbar, click the Run entire script button. The results should now include only 14 documents.

combined query results

For each document, the address.state field value is either Washington or Oregon, and the device field value contains the term iphone.

12. The next step is to limit your search results to the first, last, and user_name fields.

At the command prompt, delete the current statement and then type or paste the following command:

db.customers.find(
  {
    "address.state":{$in:["Washington", "Oregon"]},
    "device":/.*iphone.*/i
  },
  {first:1, last:1, user_name:1}
);

The find statement is the same as the preceding example except that it now includes a projection argument, which defines the three fields that should be returned in the results.

For each field, you must specify a value of 1 to indicate that the field should be included. When specifying multiple fields, you must separate them with a comma.

13. On the IntelliShell toolbar, click the Execute entire script button. The results should now be limited to the three specified fields (first, last, and user_name), as well as the _id field, which is returned by default.

The query with projection

14. The final step is to update the query so the results are sorted by the last values and then by the first values. At the command prompt, delete the current statement and then type or paste the following command:

db.customers.find(
  {
    "address.state":{$in:["Washington", "Oregon"]},
    "device":/.*iphone.*/i
  },
  {first:1, last:1, user_name:1}
).sort({last:1, first:1});

To sort the results, you add a period after the find method, followed by the sort method.

The method’s arguments include the field names, specified in the order that the documents should be sorted. The value of 1 associated with the two fields indicates that the documents should be sorted in ascending order, rather than descending, which would take a value of -1.

15. On the IntelliShell toolbar, click the Run entire script button. The results should look similar to the following figure.

Query with sort
Tree view
The 14 documents in Table View

16. At the command prompt, delete the current statement but leave IntelliShell open for the third exercise.

Previous Topic
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

    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