Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
MongoDB Fundamentals

You're reading from  MongoDB Fundamentals

Product type Book
Published in Dec 2020
Publisher Packt
ISBN-13 9781839210648
Pages 748 pages
Edition 1st Edition
Languages
Concepts
Authors (4):
Amit Phaltankar Amit Phaltankar
Profile icon Amit Phaltankar
Juned Ahsan Juned Ahsan
Profile icon Juned Ahsan
Michael Harrison Michael Harrison
Profile icon Michael Harrison
Liviu Nedov Liviu Nedov
Profile icon Liviu Nedov
View More author details

Table of Contents (15) Chapters

Preface
1. Introduction to MongoDB 2. Documents and Data Types 3. Servers and Clients 4. Querying Documents 5. Inserting, Updating, and Deleting Documents 6. Updating with Aggregation Pipelines and Arrays 7. Data Aggregation 8. Coding JavaScript in MongoDB 9. Performance 10. Replication 11. Backup and Restore in MongoDB 12. Data Visualization 13. MongoDB Case Study Appendix

1. Introduction to MongoDB

Activity 1.01: Setting Up a Movies Database

Solution:

The following steps will help you complete this activity:

  1. First, connect to your MongoDB cluster that was set up as part of Exercise 1.04, Setting Up Your First Free MongoDB Cluster on Atlas. It should look something like this:
    mongo "mongodb+srv://cluster0-zlury.mongodb.net/test" –username   <yourUsername>
  2. Enter the preceding command on your command prompt and provide the password when prompted. Upon successful login, you should see a shell prompt with your cluster name, something like this:
    MongoDB Enterprise Cluster0-shard-0:PRIMARY>
  3. Now, create the movies database and call it moviesDB. Utilize the use command:
    use moviesDB
  4. Create the movies collection with a few relevant attributes. Create the collection by inserting the documents into a non-existent collection. You are encouraged to think and implement collections with attributes that you...

2. Documents and Data Types

Activity 2.01: Modeling a Tweet into a JSON Document

Solution:

Perform the following steps to complete the activity:

  1. Identify and list the following fields from the tweet that can be included in the JSON document:
    creation date and time
    user id
    user name 
    user profile pic
    user verification status
    hash tags
    mentions
    tweet text
    likes
    comments
    retweets
  2. Group the related fields such that they can be placed as embedded objects or arrays. Since a tweet can have multiple hashtags and mentions, it can be represented as an array. The modified list appears as follows:
    creation date and time
    user 
      id
      name 
      profile pic
      verification status
    hash tags
      [tags]
    mentions
      [mentions]
    tweet text
    likes
    comments
    retweets
  3. Prepare the user object and add the values from the tweet:
    {
      "id": "Lord_Of_Winterfell",
      "name": "Office of Ned...

3. Servers and Clients

Activity 3.01: Managing Your Database Users

Solution:

The following are the detailed steps for the activity:

  1. Go to http://cloud.mongodb.com to connect to the Atlas console.
  2. Log on to your new MongoDB Atlas web interface using your username and password, which was created when you registered for the Atlas Cloud:

    Figure 3.40: MongoDB Atlas login page

  3. Create a new database called dev_mflix and, on the Atlas clusters page, click the COLLECTIONS button:

    Figure 3.41: MongoDB Atlas Clusters Page

    A window with all the collections will appear, as shown in Figure 3.42:

    Figure 3.42: MongoDB Atlas data explorer

  4. Next, click the +Create Database button, at the top of the database list. The following window will appear:

    Figure 3.43: MongoDB Create Database window

  5. Set DATABASE NAME to dev_mflix and COLLECTION NAME to dev_data01, and then click the CREATE button.
  6. Create a custom role called Developers. Click on Database Access (on the left side...

4. Querying Documents

Activity 4.01: Finding Movies by Genre and Paginating Results

Solution:

The most important part of the findMoviesByGenre function is the underlying MongoDB query. You will take a step-by-step approach to solving the problem, starting with creating the query on a mongo shell. Once the query has been prepared, you will wrap it into a function:

  1. Create a query to filter results by genre. For this activity, we are using the Action genre:
          db.movies.find(
              {"genres" : "Action"}
          )
  2. The requirement is to return only the titles of the movies. For this, add a projection to project only the title field and exclude the rest, including _id:
          db.movies.find(
              {"genres" : "Action"},
       ...

5. Inserting, Updating, and Deleting Documents

Activity 5.01: Updating Comments for Movies

Solution:

Perform the following steps to complete the activity:

  1. First, update the movie_id field in all three comments. As we need to apply the same update to all three comments, we will use the findOneAndUpdate() function along with the $set operator to change the value of the field:
    db.comments.updateMany(
      {
        "_id" : {$in : [
          ObjectId("5a9427658b0beebeb6975eb3"),
          ObjectId("5a9427658b0beebeb6975eb4"),
          ObjectId("5a9427658b0beebeb6975eaa")
        ]}
      },
      {
        $set : {"movie_id" : ObjectId("573a13abf29313caabd25582")}
      }
    )

    Using the update command, we find three movies by their _id, providing their primary keys using...

6. Updating with Aggregation Pipelines and Arrays

Activity 6.01: Adding an Actor's Name to the Cast

Solution:

Perform the following steps to complete the activity:

  1. Since only one movie document must be updated, use the findOneAndUpdate() command. Open a text editor and type the following command:
          db.movies.findOneAndUpdate({"title" : "Jurassic World"})

    This query uses a query expression based on the movie title.

  2. Prepare an update expression to insert an element into the array. As the cast array must be unique, use $addToSet, as follows:
        db.movies.findOneAndUpdate(
            {"title" : "Jurassic World"},
            {$addToSet : {"cast" : "Nick Robinson"}}
        )

    This query inserts Nick Robinson into cast and also ensures that no duplicates are inserted...

7. Data Aggregation

Activity 7.01: Putting Aggregations into Practice

Solution:

Perform the following steps to complete the activity:

  1. First, create the scaffold code:
    // Chapter_7_Activity.js
    var chapter7Activity = function() {
        var pipeline = [];
        db.movies.aggregate(pipeline).forEach(printjson);
    }
    Chapter7Activity()
  2. Add the first match for documents older than 2001:
    var pipeline = [
        {$match: {
            released: {$lte: new ISODate("2001-01-01T00:00:00Z")}
        }}
      ];
  3. Add a second match condition for movies with at least one award win:
        {$match: {
            released: {$lte: new ISODate("2001-01-01T00:00:00Z")},
            "awards.wins": {$gte: 1},
        }}
  4. Add a sort condition...

8. Coding JavaScript in MongoDB

Activity 8.01: Creating a Simple Node.js Application

Solution:

Perform the following steps to complete the activity:

  1. Import the readline and MongoDB libraries:
    const readline = require('readline');
    const MongoClient = require('mongodb').MongoClient;
  2. Create your readline interface:
    const interface = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
    });
  3. Declare any variables you will need:
    const url = 'mongodb+srv://mike:password@myAtlas-  fawxo.gcp.mongodb.net/test?retryWrites=true&w=majority';
    const client = new MongoClient(url);
    const databaseName = "sample_mflix";
    const collectionName = "movies";
  4. Create a function called list that will fetch the top five films for a given genre, returning their title, favourite, and ID fields. You will need to ask for the category in this function. Look at the login method...

9. Performance

Activity 9.01: Optimizing a Query

Solution:

Perform the following steps to complete the activity:

  1. Open your mongo shell and connect to the sample_supplies database on the Atlas cluster. First, you need to find how many records the query returns. The following snippet shows a count query, which gives the number of backpacks sold at the Denver store:
         db.sales.count(
             {
                 "items.name" : "backpack",
                 "storeLocation" : "Denver"
             }
         )
         
  2. The query returns a count of 711 records.
  3. Next, analyze the query given by the analytics team using the explain() function, and print the execution stats, as...

10. Replication

Activity 10.01: Testing a Disaster Recovery Procedure for a MongoDB Database

Solution:

Perform the following steps to complete the activity:

  1. Create the directories as follows: C:\sale\sale-prod, C:\sale\sale-dr, C:\sale\sale-ab, and C:\sale\log.

    Note

    For Linux and macOS, the directory names would be like /data/sales/sale-prod, /data/sales/sale-dr…

  2. Start the cluster nodes as follows:
    start mongod --port 27001 --bind_ip_all --replSet sale-cluster --dbpath C:\sale\sale-prod --logpath C:\sale\log\sale-prod.log --logappend --oplogSize 50
    start mongod --port 27002 --bind_ip_all --replSet sale-cluster --dbpath C:\sale\sale-dr --logpath C:\sale\log\sale-dr.log --logappend --oplogSize 50
    start mongod --port 27003 --bind_ip_all --replSet sale-cluster --dbpath C:\sale\sale-ab --logpath C:\sale\log\sale-ab.log --logappend --oplogSize 50
  3. Connect with mongo shell:
     mongo mongodb://localhost:27001/?replicaSet=sale-cluster
  4. Create and activate the cluster...

11. Backup and Restore in MongoDB

Activity 11.01: Backup and Restore in MongoDB

Solution:

Perform the following steps to complete the activity:

  1. Start with mongoexport. Remove the --db option, since you are providing it in the URI.
    mongoexport --uri=mongodb+srv://USERNAME:PASSWORD@myAtlas-fawxo.gcp.mongodb.net/sample_mflix --collection=theaters --out="theaters.csv" --type=csv --sort='{theaterId: 1}'
  2. Add the fields option to the mongoexport command
    mongoexport --uri=mongodb+srv://USERNAME:PASSWORD@myAtlas-fawxo.gcp.mongodb.net/sample_mflix --fields=theaterId,location --collection=theaters --out="theaters.csv" --type=csv --sort='{theaterId: 1}'
  3. Add the necessary CSV options to the import command, that is, type, ignoreBlanks, and headerline.
    mongoimport --uri=mongodb+srv://USERNAME:PASSWORD@myAtlas-fawxo.gcp.mongodb.net/imports --type=CSV --headerline -...

12. Data Visualization

Activity 12.01: Creating a Sales Presentation Dashboard

Solution:

Perform the following steps to complete the activity:

  1. Before you can start building the charts for this new presentation, you must define the appropriate data source in the application. Follow the steps from Exercise 12.01, Working with Data Sources, to create a new sales data source on the sales collection from the sample_supplies database, as shown in the following figure:

    Figure 12.52: Creating a new sales data source

  2. Click Finish to save. The new data source will appear in the list as can be seen in the following figure:

    Figure 12.53: Sales Data Sources

  3. From the dashboard, click on the ADD CHART button as shown in the following screenshot:

    Figure 12.54: Clicking on ADD CHART in the User's Dashboard

    In the Chart Builder, choose the sales data source, that was created in step 2 (that is, sample_supplies.sales) and then select the Circular chart type and the Donut chart...

lock icon The rest of the chapter is locked
arrow left Previous Chapter
You have been reading a chapter from
MongoDB Fundamentals
Published in: Dec 2020 Publisher: Packt ISBN-13: 9781839210648
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}