In this course we will make extensive use of MongoDB Compass for learning how to use MongoDB.
Please download Compass from the MongoDB Download Center.If you downloaded Compass before today, please make sure you are using version 1.8 or later and upgrade if necessary.
Install Compass on your computer from the download.
Launch Compass.
When Compass opens you will see a page titled “Connect to Host”.
Use the following information to complete this form, but do not click “Connect” yet.
Hostname: cluster0-shard-00-00-jxeqq.mongodb.net
Username: m001-student
Password: m001-mongodb-basics
Replica Set Name: Cluster0-shard-0
Read Preference: Primary Preferred
Click “Add to Favorites” and enter M001 RS as the Favorite Name. Adding this connection as a favorite will enable you to easily connect to our class MongoDB deployment after closing and restarting Compass at some point in the future.
Now, click “Connect” and load the databases in the M001 class MongoDB deployment.
Databases - Documents - Collections
Documents Types
Documents: Scalar Value Types
Based on the Compass schema view, there are two value types found in documents for this field: int32 and String. The label “Year” indicates the name of the field, not a data type.
MongoDB provides specific support for documents, arrays, and geospatial data.
Documents: Fields with Documents as Values
Documents: Fields with Arrays as Values
Documents: Fields with Geospatial Data
Filtering Collections with Queries
Geospatial Queries
In Compass, navigate to either the schema view or the documents view for the ships.shipwrecks collection. To get the correct answer, locate Cancun, Mexico on the map for the coordinates field. Click on the name, “Cancun” on the map, press the shift key on your keyboard and drag your mouse to a radius that encompasses the coast of Cancun. Click the “APPLY” button near the filter form field. I found three shipwrecks.
Chapter02 MongoDB Query Language + Atlas
Installing the mongo Shell (OSX/Linux)
download from here a list of script program, see below
setting the path of the about program into .bash_profile
verify
1 2 3
$ mongo --nodb MongoDB shell version v3.6.2 >
Connecting to Our Class Atlas Cluster from the mongo Shell
Please use the following command to connect to the class Atlas cluster. You should issue this command in the cmd shell, the OSX Terminal application, or another command-line interface of your choice.
➜ ~ mongo "mongodb://cluster0-shard-00-00-jxeqq.mongodb.net:27017,cluster0-shard-00-01-jxeqq.mongodb.net:27017,cluster0-shard-00-02-jxeqq.mongodb.net:27017/test?replicaSet=Cluster0-shard-0" --authenticationDatabase admin --ssl --username m001-student --password m001-mongodb-basics MongoDB shell version v3.6.2 connecting to: mongodb://cluster0-shard-00-00-jxeqq.mongodb.net:27017,cluster0-shard-00-01-jxeqq.mongodb.net:27017,cluster0-shard-00-02-jxeqq.mongodb.net:27017/test?replicaSet=Cluster0-shard-0 2018-01-19T17:42:03.869+1100 I NETWORK [thread1] Starting new replica set monitor for Cluster0-shard-0/cluster0-shard-00-00-jxeqq.mongodb.net:27017,cluster0-shard-00-01-jxeqq.mongodb.net:27017,cluster0-shard-00-02-jxeqq.mongodb.net:27017 2018-01-19T17:42:05.353+1100 I NETWORK [thread1] Successfully connected to cluster0-shard-00-01-jxeqq.mongodb.net:27017 (1 connections now open to cluster0-shard-00-01-jxeqq.mongodb.net:27017 with a 5 second timeout) 2018-01-19T17:42:05.533+1100 I NETWORK [ReplicaSetMonitor-TaskExecutor-0] Successfully connected to cluster0-shard-00-00-jxeqq.mongodb.net:27017 (1 connections now open to cluster0-shard-00-00-jxeqq.mongodb.net:27017 with a 5 second timeout) 2018-01-19T17:42:08.449+1100 I NETWORK [ReplicaSetMonitor-TaskExecutor-0] Successfully connected to cluster0-shard-00-02-jxeqq.mongodb.net:27017 (1 connections now open to cluster0-shard-00-02-jxeqq.mongodb.net:27017 with a 5 second timeout) MongoDB server version: 3.4.10 WARNING: shell and server versions do not match Cluster0-shard-0:PRIMARY> show collections Cluster0-shard-0:PRIMARY> show dbs 100YWeatherSmall 0.127GB admin 0.000GB aggregations 0.067GB citibike 0.334GB city 0.002GB coursera-agg 0.083GB local 1.089GB mflix 0.288GB results 0.000GB ships 0.001GB video 0.238GB Cluster0-shard-0:PRIMARY> use 100YWeatherSmall switched to db 100YWeatherSmall Cluster0-shard-0:PRIMARY> show collections data Cluster0-shard-0:PRIMARY>
Here’s a question? When connecting to an Atlas cluster using the shell, why do we provide the hostnames for all nodes when we launch mongo?
Answer: If the primary node goes down, the shell can connect to other nodes in the cluster instead.
The Atlas clusters we’ve looked at are replica sets. Replica sets are designed so that if the primary node goes down, one of the other nodes will step up to take its place so that clients can continue reading and writing data as if nothing had happened. The mongo shell is one such client.
See the replication documentation for more information.
Detailed instructions for creating a sandbox cluster can be found in the lab immediately following this lesson.
Please note that, while we’ve labeled this as a lab, it is ungraded. This writeup is here simply to get you started on creating an Atlas cluster.
Go to https://cloud.mongodb.com/links/registerForAtlas and complete the account creation form you see on that page. Please make sure you see the message “Sign up for MongoDB Atlas” at the top of the page.
Once you have completed the registration form, in the next page that appears, you will be asked to choose a new group name. We use groups to manage access to Atlas clusters. Please use the name, m001-sandbox.
Once you have created a group, in the next page, enter the name, Sandbox for your cluster. On the same page, select the M0 instance size. Note that the “Pricing” now changes to say “$0.00/forever”. You do NOT need to enter a credit card to create a free-tier Atlas cluster (M0). They are free. Scroll to the bottom of the cluster-creation form and enter an administrative username and password. Please enter the username, m001-student and the password, m001-mongodb-basics.
Once you’ve entered your username and password, click Confirm & Deploy. You will need to wait a few minutes for your cluster to be spun up. Once your cluster is ready, click on the Security tab and then on the IP Whitelist tab. Click the ADD IP ADDRESS button and, then, in the modal that pops up, click ALLOW ACCESS FROM ANYWHERE. Click the CONFIRM button and wait while the security settings for your cluster are configured.
Don’t forget to do this. Note that we do not generally recommend opening an Atlas cluster to allow access from anywhere. We do that for this class to minimize network issues that you might run into.
getting into the place the js is stored on your local computer
connect to my remote cluster as we do in the last section
load loacl data into remote cluster database
1 2 3 4 5 6 7 8 9 10 11 12
Cluster0-shard-0:PRIMARY> load("loadMovieDetailsDataset.js") Cluster0-shard-0:PRIMARY> true Cluster0-shard-0:PRIMARY> show dbs admin 0.000GB local 1.756GB video 0.001GB Cluster0-shard-0:PRIMARY> use video switched to db video Cluster0-shard-0:PRIMARY> show collections movieDetails Cluster0-shard-0:PRIMARY> db.movieDetails.find().pretty() ...
Connecting to Your Sandbox Cluster from Compass
Find hostname and port, and type in username and password.
Use these information to set your configuration of Compass.
Creating Documents: insertOne()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Cluster0-shard-0:PRIMARY> show dbs admin 0.000GB local 2.904GB video 0.001GB Cluster0-shard-0:PRIMARY> use video switched to db video Cluster0-shard-0:PRIMARY> show collections movieDetails movieScratch Cluster0-shard-0:PRIMARY> db video Cluster0-shard-0:PRIMARY> db.movies.insertOne({title: "Star Trek II: The Wrath of Khan", year: 1982, imdb: "tt0084726"}) { "acknowledged" : true, "insertedId" : ObjectId("5a6421f6ad80d9a686a6d2de") } Cluster0-shard-0:PRIMARY> db.movies.insertOne({_id: "tt0084726", title: "Star Trek II: The Wrath of Khan", year: 1982, imdb: "tt0084726"}) { "acknowledged" : true, "insertedId" : "tt0084726" } Cluster0-shard-0:PRIMARY>
MongoDB or the client will create an _id for us if we do not supply one.
We can supply an _id for the document
Both mongo shell and Compass support the ability to insert single documents.
All _id values within a single collection must be unique.
_id values created for us by MongoDB are of type ObjectId not int32.
Cluster0-shard-0:PRIMARY> db.movies.find({mpaaRating:"PG-13", year:2009}).pretty() { "_id" : ObjectId("58c59c8f99d4ee0af9e5aede"), "title" : "The Box", "year" : 2009, "imdbId" : "tt0362478", "mpaaRating" : "PG-13", "genre" : "Drama, Mystery, Sci-Fi", "viewerRating" : 5.6, "viewerVotes" : 72088, "runtime" : 115, "director" : "Richard Kelly", "cast" : [ "Cameron Diaz", "James Marsden", "Frank Langella", "James Rebhorn" ], "plot" : "A small wooden box arrives on the doorstep of a married couple, who know that opening it wi ll grant them a million dollars and kill someone they don't know.", "language" : "English" } ...
= {“attribute.subattribute” : value, …} , do not forget the double quotes
Excercise 1
Explore the movieDetails collection that you loaded into your Atlas sandbox cluster and then issue a query to answer the following question. How many movies in the movieDetails collection have exactly 2 award wins and 2 award nominations?
You can find this answer in either the mongo shell or in Compass.
In the shell, assuming you’ve loaded movieDetails into the video database and assuming you are connected to your Atlas sandbox cluster, you can issue the following query.
In Compass you can use the following filter in the Documents tab for the movieDetails collection.
{awards.wins: 2, awards.nominations: 2}
Excercise 2
Explore the movieDetails collection that you loaded into your Atlas sandbox cluster and then issue a query to answer the following question. How many movies in the movieDetails collection are rated PG and have exactly 10 award nominations?
MongoDB use find to do query. (collection must be specific)
db.collection.find()
= {attribute: value, …}
= {“attribute.subattribute” : value, …} do not forget the double quotes
= array query
= {“array_attribute” : value, …} do not forget the double quotes
= {“array_attribute” : [value1, value2, …], …} do not forget the double quotes && query result will follow the order in [] as well
= {“array_attribute.index” : value, …} do not forget the double quotes
Excercise 1
Explore the movieDetails collection that you loaded into your Atlas sandbox cluster and then issue a query to answer the following question. How many documents list just two writers: “Ethan Coen” and “Joel Coen”, in that order?
You can find this answer in either the mongo shell or in Compass.
In the shell, assuming you’ve loaded movieDetails into the video database and assuming you are connected to your Atlas sandbox cluster, you can issue the following query.
In Compass you can use the following filter in the Documents tab for the movieDetails collection.
{writers: ["Ethan Coen", "Joel Coen"]}
Excercise 2
Explore the movieDetails collection that you loaded into your Atlas sandbox cluster and then issue a query to answer the following question. How many movies in the movieDetails collection list “Family” among its genres?
the first result 8 means the first element in array has to be Family
the second result 124 means it is enough to contain Family in the genres
so 124 is correct answer
Excercise 3
Explore the movieDetails collection that you loaded into your Atlas sandbox cluster and then issue a query to answer the following question. How many movies in the movieDetails collection list “Western” second among its genres?
A cursor is essentially a pointer to the current location in the result set. We use the cursor to iterate the returned result. The cursor could get 20 records back to the client. If there is some more, it will request the rest of records.
For update operations, update operators specify how to modify specific fields in documents matching a filter. Fields may be added, deleted, or have their value changed in some way. Update operators define what modifications to make with respect to one or more fields in matching documents.
MongoDB Enterprise > db.movieDetails.find({runtime:{$gt: 90}}, {_id:0, title:1}) { "title" : "Be Cool" } { "title" : "Ah, Wilderness!" } { "title" : "Ai Weiwei: Never Sorry" } { "title" : "I Am Legend" } { "title" : "A.I. Artificial Intelligence" } { "title" : "Un'estate ai Caraibi" } { "title" : "I Am Number Four" } { "title" : "Who Am I" } { "title" : "Al Capone" } { "title" : "The Ax" } { "title" : "Az alkimista és a szüz" } { "title" : "My Super Ex-Girlfriend" } { "title" : "Ex" } { "title" : "E.T. the Extra-Terrestrial" } { "title" : "Poulet au vinaigre" } { "title" : "La cuisine au beurre" } { "title" : "Clipped Wings They Do Fly Music CD" } { "title" : "Une journée bien remplie ou Neuf meurtres insolites dans une même journée par un seul homme dont ce n'est pas le métier" } { "title" : "Nos héros sont morts ce soir" } { "title" : "Ci hai rotto papà" } Type "it"for more MongoDB Enterprise > db.movieDetails.find({runtime:{$gt: 90, $lt : 120}}, {_id:0, title:1}) { "title" : "Be Cool" } { "title" : "Ah, Wilderness!" } { "title" : "Ai Weiwei: Never Sorry" } { "title" : "I Am Legend" } { "title" : "Un'estate ai Caraibi" } { "title" : "I Am Number Four" } { "title" : "Who Am I" } { "title" : "Al Capone" } { "title" : "The Ax" } { "title" : "Az alkimista és a szüz" } { "title" : "My Super Ex-Girlfriend" } { "title" : "E.T. the Extra-Terrestrial" } { "title" : "Poulet au vinaigre" } { "title" : "La cuisine au beurre" } { "title" : "Clipped Wings They Do Fly Music CD" } { "title" : "Une journée bien remplie ou Neuf meurtres insolites dans une même journée par un seul homme dont ce n'est pas le métier" } { "title" : "Nos héros sont morts ce soir" } { "title" : "Ci hai rotto papà" } { "title" : "Ci vediamo domani" } { "title" : "La dottoressa ci sta col colonnello" } Type "it"for more
MongoDB Enterprise > db.movieDetails.find({rated: {$ne: "UNRATED"}}, {_id: 0, title: 1, rated: 1}) { "title" : "Be Cool", "rated" : "PG-13" } { "title" : "Don't Be a Menace to South Central While Drinking Your Juice in the Hood", "rated" : "R" } { "title" : "Ah Müjgan Ah", "rated" : null } { "title" : "Ah, Wilderness!", "rated" : "PASSED" } { "title" : "Ai Weiwei: Never Sorry", "rated" : "R" } { "title" : "I Am Legend", "rated" : "PG-13" } { "title" : "A.I. Artificial Intelligence", "rated" : "PG-13" } { "title" : "Un'estate ai Caraibi", "rated" : null } { "title" : "I Am Number Four", "rated" : "PG-13" } { "title" : "Who Am I", "rated" : null } { "title" : "I Am David", "rated" : "PG" } { "title" : "Al Capone", "rated" : "APPROVED" } { "title" : "Saluda al diablo de mi parte", "rated" : null } { "title" : "The Ax", "rated" : null } { "title" : "Az alkimista és a szüz", "rated" : null } { "title" : "The Ax Fight", "rated" : null } { "title" : "Az igazi Mao", "rated" : null } { "title" : "Clara et moi", "rated" : null } { "title" : "My Super Ex-Girlfriend", "rated" : "PG-13" } { "title" : "The Ex", "rated" : "PG-13" } Type "it"for more MongoDB Enterprise > db.movieDetails.find({rated: {$in: ["PG","R"]}}, {_id: 0, title: 1, rated: 1}) { "title" : "Don't Be a Menace to South Central While Drinking Your Juice in the Hood", "rated" : "R" } { "title" : "Ai Weiwei: Never Sorry", "rated" : "R" } { "title" : "I Am David", "rated" : "PG" } { "title" : "E.T. the Extra-Terrestrial", "rated" : "PG" } { "title" : "An American Werewolf in London", "rated" : "R" } { "title" : "C.C. & Company", "rated" : "R" } { "title" : "Red Rock West", "rated" : "R" } { "title" : "Star Wars: Episode IV - A New Hope", "rated" : "PG" } { "title" : "Star Wars: Episode VI - Return of the Jedi", "rated" : "PG" } { "title" : "Star Wars: Episode I - The Phantom Menace", "rated" : "PG" } { "title" : "Star Wars: Episode II - Attack of the Clones", "rated" : "PG" } { "title" : "Dr. Strangelove or: How I Learned to Stop Worrying and Love the Bomb", "rated" : "PG" } { "title" : "Shakespeare in Love", "rated" : "R" } { "title" : "I Love You, Man", "rated" : "R" } { "title" : "From Paris with Love", "rated" : "R" } { "title" : "I Love You Phillip Morris", "rated" : "R" } { "title" : "Office Space", "rated" : "R" } { "title" : "Zathura: A Space Adventure", "rated" : "PG" } { "title" : "2001: A Space Travesty", "rated" : "R" } { "title" : "The Adventures of Tintin", "rated" : "PG" } Type "it"for more
Quiz Using the $in operator, filter the video.movieDetails collection to determine how many movies list either “Ethan Coen” or “Joel Coen” among their writers. Your filter should match all movies that list either of the Coen brothers as writers regardless of how many other writers are also listed. Select the number of movies matching this filter from the choices below. Check all that apply:
You can find this answer in the mongo shell or in Compass.
In the mongo shell, assuming you’ve loaded movieDetails into the video database and assuming you are connected to your Atlas sandbox cluster, you can issue the following commands.
➜ video mongo "mongodb://cluster0-shard-00-00-jxeqq.mongodb.net:27017,cluster0-shard-00-01-jxeqq.mongodb.net:27017,cluster0-shard-00-02-jxeqq.mongodb.net:27017/test?replicaSet=Cluster0-shard-0" --authenticationDatabase admin --ssl --username m001-student --password m001-mongodb-basics MongoDB shell version v3.6.2 connecting to: mongodb://cluster0-shard-00-00-jxeqq.mongodb.net:27017,cluster0-shard-00-01-jxeqq.mongodb.net:27017,cluster0-shard-00-02-jxeqq.mongodb.net:27017/test?replicaSet=Cluster0-shard-0 2018-01-28T17:36:17.557+1100 I NETWORK [thread1] Starting new replica set monitor for Cluster0-shard-0/cluster0-shard-00-00-jxeqq.mongodb.net:27017,cluster0-shard-00-01-jxeqq.mongodb.net:27017,cluster0-shard-00-02-jxeqq.mongodb.net:27017 2018-01-28T17:36:18.673+1100 I NETWORK [ReplicaSetMonitor-TaskExecutor-0] Successfully connected to cluster0-shard-00-02-jxeqq.mongodb.net:27017 (1 connections now open to cluster0-shard-00-02-jxeqq.mongodb.net:27017 with a 5 second timeout) 2018-01-28T17:36:18.696+1100 I NETWORK [thread1] Successfully connected to cluster0-shard-00-00-jxeqq.mongodb.net:27017 (1 connections now open to cluster0-shard-00-00-jxeqq.mongodb.net:27017 with a 5 second timeout) 2018-01-28T17:36:20.112+1100 I NETWORK [ReplicaSetMonitor-TaskExecutor-0] Successfully connected to cluster0-shard-00-01-jxeqq.mongodb.net:27017 (1 connections now open to cluster0-shard-00-01-jxeqq.mongodb.net:27017 with a 5 second timeout) MongoDB server version: 3.4.10 WARNING: shell and server versions do not match Cluster0-shard-0:PRIMARY> Cluster0-shard-0:PRIMARY> Cluster0-shard-0:PRIMARY> use video switched to db video Cluster0-shard-0:PRIMARY> db.movies.find({viewerRating: {$type: "double"}}).count() 301791
Quiz
Connect to our class Atlas cluster from the mongo shell or Compass and answer the following question. How many documents in the 100YWeatherSmall.data collection do NOT contain the key atmosphericPressureChange.
Connect to our class Atlas cluster from the mongo shell or Compass and view the ships.shipwrecks collection. In this collection, watlev describes the water level at the shipwreck site and depth describes how far below sea level the ship rests. How many documents in the ships.shipwrecks collection match either of the following criteria: watlev equal to “always dry” or depth equal to 0. Choose the best answer:
Connect to our class Atlas cluster from the mongo shell or Compass and view the 100YWeatherSmall.data collection. The sections field in this collection identifies supplementary readings available in a given document by a three-character code. How many documents list: “AG1”, “MD1”, and “OA1” among the codes in their sections array. Your count should include all documents that include these three codes regardless of what other codes are also listed. Choose the best answer:
You can find this answer in the mongo shell or in Compass.
In the mongo shell, assuming you’ve connected to the M001 class Atlas cluster, you can issue the following commands to find this value.
use 100YWeatherSmall
db.data.find({sections: {$all: ["AG1", "MD1", "OA1"]}}).count()
In Compass, navigate to the 100YWeatherSmall.data collection and then apply the following filter in either the Schema or Documents view.
Connect to our class Atlas cluster from the mongo shell or Compass and view the 100YWeatherSmall.data collection. How many documents in this collection contain exactly two elements in the sections array field? Choose the best answer:
You can find this answer in the mongo shell or in Compass.
In the mongo shell, assuming you’ve connected to the M001 class Atlas cluster, you can issue the following commands to find this value.
use 100YWeatherSmall
db.data.find({sections: {$size: 2}}).count()
In Compass, navigate to the 100YWeatherSmall.data collection and then apply the following filter in either the Schema or Documents view.
MongoDB Enterprise > martian = db.movieDetails.findOne({title: "The Martian"}) { "_id" : ObjectId("569520be699edceab722522a"), "title" : "The Martian", "year" : 2015, "rated" : "PG-13", "released" : ISODate("2015-10-02T04:00:00Z"), "runtime" : 144, "countries" : [ "USA", "UK" ], "genres" : [ "Adventure", "Drama", "Sci-Fi" ], "director" : "Ridley Scott", "writers" : [ "Drew Goddard", "Andy Weir" ], "actors" : [ "Matt Damon", "Jessica Chastain", "Kristen Wiig", "Jeff Daniels" ], "plot" : "During a manned mission to Mars, Astronaut Mark Watney is presumed dead after a fierce storm and left behind by his crew. But Watney has survived and finds himself stranded and alone on the hostile planet. With only meager supplies, he must draw upon his ingenuity, wit and spirit to subsist and find a way to signal to Earth that he is alive.", "poster" : "http://ia.media-imdb.com/images/M/MV5BMTc2MTQ3MDA1Nl5BMl5BanBnXkFtZTgwODA3OTI4NjE@._V1_SX300.jpg", "imdb" : { "id" : "tt3659388", "rating" : 8.2, "votes" : 187881 }, "tomato" : { "meter" : 93, "image" : "certified", "rating" : 7.9, "reviews" : 280, "fresh" : 261, "consensus" : "Smart, thrilling, and surprisingly funny, The Martian offers a faithful adaptation of the bestselling book that brings out the best in leading man Matt Damon and director Ridley Scott.", "userMeter" : 92, "userRating" : 4.3, "userReviews" : 104999 }, "metacritic" : 80, "awards" : { "wins" : 8, "nominations" : 14, "text" : "Nominated for 3 Golden Globes. Another 8 wins & 14 nominations." }, "type" : "movie" } MongoDB Enterprise > MongoDB Enterprise > martian.boxOffice = [ ... {"country": "USA", "revenue": 228.4}, ... {"country": "Australia", "revenue": 19.6}, ... {"country": "UK", "revenue": 33.9}, ... {"country": "Germany", "revenue": 16.2}, ... {"country": "France", "revenue": 19.8} ... ] [ { "country" : "USA", "revenue" : 228.4 }, { "country" : "Australia", "revenue" : 19.6 }, { "country" : "UK", "revenue" : 33.9 }, { "country" : "Germany", "revenue" : 16.2 }, { "country" : "France", "revenue" : 19.8 } ] MongoDB Enterprise > delete martian._id; true MongoDB Enterprise > db.movieDetails.insertOne(martian); { "acknowledged" : true, "insertedId" : ObjectId("5a6d7ce60302cd546905b3f2") } MongoDB Enterprise > MongoDB Enterprise > db.movieDetails.find({"boxOffice.country": "Germany", "boxOffice.revenue": {$gt: 17}}, {boxOffice: 1}).pretty() { "_id" : ObjectId("5a6d7ce60302cd546905b3f2"), "boxOffice" : [ { "country" : "USA", "revenue" : 228.4 }, { "country" : "Australia", "revenue" : 19.6 }, { "country" : "UK", "revenue" : 33.9 }, { "country" : "Germany", "revenue" : 16.2 }, { "country" : "France", "revenue" : 19.8 } ] } MongoDB Enterprise > db.movieDetails.find({boxOffice: {$elemMatch: {"country": "Germany", "revenue": {$gt: 16}}}}, {boxOffice: 1}).pretty() { "_id" : ObjectId("5a6d7ce60302cd546905b3f2"), "boxOffice" : [ { "country" : "USA", "revenue" : 228.4 }, { "country" : "Australia", "revenue" : 19.6 }, { "country" : "UK", "revenue" : 33.9 }, { "country" : "Germany", "revenue" : 16.2 }, { "country" : "France", "revenue" : 19.8 } ] }
Quiz
In the M001 class Atlas cluster you will find a database added just for this week of the course. It is called results. Within this database you will find two collections: surveys and scores. Documents in the results.surveys collection have the following schema.
{_id: ObjectId(“5964e8e5f0df64e7bc2d7373”), results: [{product: “abc”, score: 10}, {product: “xyz”, score: 9}]} The field called results that has an array as its value. This array contains survey results for products and lists the product name and the survey score for each product.
How many documents in the results.surveys collection contain a score of 7 for the product, “abc”?
You can find this answer in the mongo shell or in Compass.
In the mongo shell, assuming you’ve connected to the M001 class Atlas cluster, you can issue the following commands to find this value.
use results
db.surveys.find({results: {$elemMatch: {product: "abc", score: 7}}}).count() Note that it is incorrect to use the following query.
db.surveys.find({"results.product": "abc", "results.score": 7}) because in addition to correct results, this will return the document.
{"_id": 4, "results": [{"product": "abc", "score": 8}, {"product": "xyz", "score": 7}]} This document does contain an entry for “abc” and a score of 7 in the results array, but the 7 is the score of the “xyz” product, not “abc”.
In Compass, navigate to the results.surveys collection and then apply the following filter in either the Schema or Documents view.
Challenge Problem: SIngle Value in an Array of Integers
This problem is provided as a supplementary learning opportunity. It is somewhat more challenging that the ordinary labs. It is ungraded. We do not ask you submit an answer.
In the M001 class Atlas cluster you will find a database added just for this week of the course. It is called results. Within this database you will find two collections: surveys and scores. Documents in the results.scores collection have the following schema.
Connect to our class Atlas cluster from the mongo shell or Compass and view the results.scores collection. How many documents contain at least one score in the results array that is greater than or equal to 70 and less than 80?