0%

MongoDB Basic

Version: MongoDB 3.6

all the materials

Chapter01 Introduction

Connecting to MongoDB Using Compass

In this course we will make extensive use of MongoDB Compass for learning how to use MongoDB.

  1. 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.

  2. Install Compass on your computer from the download.

  3. Launch Compass.

    When Compass opens you will see a page titled “Connect to Host”.

    MongoDB Compass

  1. 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

  2. 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.

  3. 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)

  1. download from here
    a list of script program, see below

  2. setting the path of the about program into .bash_profile

  3. 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.

1
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
➜  ~ 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.

Creating an Atlas Sandbox Cluster

To begin creating your Atlas Sandbox cluster, visit https://cloud.mongodb.com/links/registerForAtlas and complete the account creation form you see on that page.

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.

Loading Data into Your Sandbox Cluster

Assume we have dataset loadMovieDetailsDataset.js

  • 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.

Creating Documents: insertMany()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
Cluster0-shard-0:PRIMARY> db.moviesScratch.insertMany(
... [
... {
... "_id" : "tt0084726",
... "title" : "Star Trek II: The Wrath of Khan",
... "year" : 1982,
... "type" : "movie"
... },
... {
... "_id" : "tt0796366",
... "title" : "Star Trek",
... "year" : 2009,
... "type" : "movie"
... },
... {
... "_id" : "tt0084726",
... "title" : "Star Trek II: The Wrath of Khan",
... "year" : 1982,
... "type" : "movie"
... },
... {
... "_id" : "tt1408101",
... "title" : "Star Trek Into Darkness",
... "year" : 2013,
... "type" : "movie"
... },
... {
... "_id" : "tt0117731",
... "title" : "Star Trek: First Contact",
... "year" : 1996,
... "type" : "movie"
... }
... ]
... );
2018-01-21T16:40:49.023+1100 E QUERY [thread1] BulkWriteError: write error at item 2 in bulk operation :
BulkWriteError({
"writeErrors" : [
{
"index" : 2,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: 5a6196a4c0c6e36a2eaf1b4c_video.moviesScratch index: _id_ dup key: { : \"tt0084726\" }",
"op" : {
"_id" : "tt0084726",
"title" : "Star Trek II: The Wrath of Khan",
"year" : 1982,
"type" : "movie"
}
}
],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
BulkWriteError@src/mongo/shell/bulk_api.js:369:48
BulkWriteResult/this.toError@src/mongo/shell/bulk_api.js:333:24
Bulk/this.execute@src/mongo/shell/bulk_api.js:1177:1
DBCollection.prototype.insertMany@src/mongo/shell/crud_api.js:314:5
@(shell):1:1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
Cluster0-shard-0:PRIMARY> db.moviesScratch.insertMany(
... [
... {
... "_id" : "tt0084726",
... "title" : "Star Trek II: The Wrath of Khan",
... "year" : 1982,
... "type" : "movie"
... },
... {
... "_id" : "tt0796366",
... "title" : "Star Trek",
... "year" : 2009,
... "type" : "movie"
... },
... {
... "_id" : "tt0084726",
... "title" : "Star Trek II: The Wrath of Khan",
... "year" : 1982,
... "type" : "movie"
... },
... {
... "_id" : "tt1408101",
... "title" : "Star Trek Into Darkness",
... "year" : 2013,
... "type" : "movie"
... },
... {
... "_id" : "tt0117731",
... "title" : "Star Trek: First Contact",
... "year" : 1996,
... "type" : "movie"
... }
... ],
... {
... "ordered": false
... }
... );
2018-01-21T16:43:42.612+1100 E QUERY [thread1] BulkWriteError: 3 write errors in bulk operation :
BulkWriteError({
"writeErrors" : [
{
"index" : 0,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: 5a6196a4c0c6e36a2eaf1b4c_video.moviesScratch index: _id_ dup key: { : \"tt0084726\" }",
"op" : {
"_id" : "tt0084726",
"title" : "Star Trek II: The Wrath of Khan",
"year" : 1982,
"type" : "movie"
}
},
{
"index" : 1,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: 5a6196a4c0c6e36a2eaf1b4c_video.moviesScratch index: _id_ dup key: { : \"tt0796366\" }",
"op" : {
"_id" : "tt0796366",
"title" : "Star Trek",
"year" : 2009,
"type" : "movie"
}
},
{
"index" : 2,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: 5a6196a4c0c6e36a2eaf1b4c_video.moviesScratch index: _id_ dup key: { : \"tt0084726\" }",
"op" : {
"_id" : "tt0084726",
"title" : "Star Trek II: The Wrath of Khan",
"year" : 1982,
"type" : "movie"
}
}
],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
BulkWriteError@src/mongo/shell/bulk_api.js:369:48
BulkWriteResult/this.toError@src/mongo/shell/bulk_api.js:333:24
Bulk/this.execute@src/mongo/shell/bulk_api.js:1177:1
DBCollection.prototype.insertMany@src/mongo/shell/crud_api.js:314:5
@(shell):1:1

区别就是:
ordered: 按顺序一条条插入,遇到error就停止了
unordered: 不需要按顺序一条条插入,所以中途有error的语句就跳过,执行下一条

Queries on Scalar Fields

use movies db

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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"
}
...

use 100YWeatherSmall db

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
Cluster0-shard-0:PRIMARY> db.data.find({"wind.direction.angle":290}).limit(1).pretty()
{
"_id" : ObjectId("5553a98ce4b02cf7150dee3c"),
"st" : "x-00700+086000",
"ts" : ISODate("1984-01-01T00:00:00Z"),
"position" : {
"type" : "Point",
"coordinates" : [
86,
-0.7
]
},
"elevation" : 9999,
"callLetters" : "PHQK",
"qualityControlProcess" : "V020",
"dataSource" : "4",
"type" : "FM-13",
"airTemperature" : {
"value" : 27.5,
"quality" : "1"
},
"dewPoint" : {
"value" : 999.9,
"quality" : "9"
},
"pressure" : {
"value" : 1012.2,
"quality" : "1"
},
"wind" : {
"direction" : {
"angle" : 290,
"quality" : "1"
},
"type" : "N",
"speed" : {
"rate" : 2.6,
"quality" : "1"
}
},
"visibility" : {
"distance" : {
"value" : 20000,
"quality" : "1"
},
"variability" : {
"value" : "N",
"quality" : "9"
}
},
"skyCondition" : {
"ceilingHeight" : {
"value" : 22000,
"quality" : "1",
"determination" : "C"
},
"cavok" : "N"
},
"sections" : [
"AG1",
"AY1",
"GF1",
"MW1"
],
"precipitationEstimatedObservation" : {
"discrepancy" : "0",
"estimatedWaterDepth" : 999
},
"pastWeatherObservationManual" : [
{
"atmosphericCondition" : {
"value" : "1",
"quality" : "1"
},
"period" : {
"value" : 6,
"quality" : "1"
}
}
],
"skyConditionObservation" : {
"totalCoverage" : {
"value" : "00",
"opaque" : "99",
"quality" : "1"
},
"lowestCloudCoverage" : {
"value" : "00",
"quality" : "1"
},
"lowCloudGenus" : {
"value" : "00",
"quality" : "1"
},
"lowestCloudBaseHeight" : {
"value" : 99999,
"quality" : "9"
},
"midCloudGenus" : {
"value" : "00",
"quality" : "1"
},
"highCloudGenus" : {
"value" : "00",
"quality" : "1"
}
},
"presentWeatherObservationManual" : [
{
"condition" : "15",
"quality" : "1"
}
]
}
Cluster0-shard-0:PRIMARY>
  • MongoDB use find to do query.
    • db.collection.find()
      • = {attribute: value, …}
      • = {“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?

1
2
3
Cluster0-shard-0:PRIMARY> db.movieDetails.find({"awards.wins":2, "awards.nominations":2}).count()
12
Cluster0-shard-0:PRIMARY>

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.

    db.movieDetails.find({"awards.wins": 2, "awards.nominations": 2}).count()

  • 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?

1
2
Cluster0-shard-0:PRIMARY> db.movieDetails.find({"rated":"PG", "awards.nominations":10}).count()
3

Queries on Array Fields

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?

1
2
3
Cluster0-shard-0:PRIMARY> db.movieDetails.find({"writers":["Ethan Coen","Joel Coen"]}).count()
1
Cluster0-shard-0:PRIMARY>

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.

    db.movieDetails.find({writers: ["Ethan Coen", "Joel Coen"]}).count()

  • 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?

1
2
3
4
5
Cluster0-shard-0:PRIMARY> db.movieDetails.find({"genres":["Family"]}).count()
8
Cluster0-shard-0:PRIMARY> db.movieDetails.find({"genres":"Family"}).count()
124
Cluster0-shard-0:PRIMARY>

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?

1
2
3
Cluster0-shard-0:PRIMARY> db.movieDetails.find({"genres.1":"Western"}).count()
14
Cluster0-shard-0:PRIMARY>

The answer is 14.

Cursors

Find method returns a cursor.

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.

it - cursor, equal to iterator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
Cluster0-shard-0:PRIMARY> db.movies.find({genre:"Action, Adventure"},{title:1})
{ "_id" : ObjectId("58c59c6a99d4ee0af9e0d117"), "title" : "Who Will Marry Mary?" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0d9c2"), "title" : "The New Exploits of Elaine" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0db62"), "title" : "The Ventures of Marguerite" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0dde5"), "title" : "The Iron Claw" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0dc25"), "title" : "Beatrice Fairfax" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0e28d"), "title" : "The Great Secret" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0e482"), "title" : "The Seven Pearls" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0e5f3"), "title" : "The Brass Bullet" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0e459"), "title" : "The Red Ace" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0e977"), "title" : "Wolves of Kultur" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0e8f3"), "title" : "Tarzan of the Apes" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0e71f"), "title" : "The Iron Test" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0e884"), "title" : "The Romance of Tarzan" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0ec74"), "title" : "Perils of Thunder Mountain" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0ea8d"), "title" : "The Fatal Fortune" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0f083"), "title" : "The Revenge of Tarzan" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0efa9"), "title" : "The Lost City" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0f0b7"), "title" : "The Screaming Shadow" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0f0cf"), "title" : "The Son of Tarzan" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0f1a1"), "title" : "The Adventures of Tarzan" }
Type "it" for more
Cluster0-shard-0:PRIMARY> it
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0f30d"), "title" : "The Hope Diamond Mystery" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0f3cc"), "title" : "The Murder of General Gryaznov" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0f3d3"), "title" : "The Mysterious Pearl" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0f876"), "title" : "The Timber Queen" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0f8e6"), "title" : "With Stanley in Africa" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0fb5e"), "title" : "Ruth of the Range" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0fc41"), "title" : "Air Hawk" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e10119"), "title" : "The Green Archer" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e10267"), "title" : "Orochi" }
{ "_id" : ObjectId("58c59c6c99d4ee0af9e1047a"), "title" : "Crossed Signals" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e10219"), "title" : "The Mystery Box" }
{ "_id" : ObjectId("58c59c6c99d4ee0af9e1087f"), "title" : "The Crimson Flash" }
{ "_id" : ObjectId("58c59c6c99d4ee0af9e10741"), "title" : "Tentacles of the North" }
{ "_id" : ObjectId("58c59c6c99d4ee0af9e108ac"), "title" : "The Down Grade" }
{ "_id" : ObjectId("58c59c6c99d4ee0af9e10766"), "title" : "Trooper 77" }
{ "_id" : ObjectId("58c59c6c99d4ee0af9e1079c"), "title" : "White Mice" }
{ "_id" : ObjectId("58c59c6c99d4ee0af9e10989"), "title" : "The King of the Jungle" }
{ "_id" : ObjectId("58c59c6c99d4ee0af9e10b2c"), "title" : "Tarzan and the Golden Lion" }
{ "_id" : ObjectId("58c59c6c99d4ee0af9e10f1e"), "title" : "Tarzan the Mighty" }
{ "_id" : ObjectId("58c59c6c99d4ee0af9e11301"), "title" : "Tarzan the Tiger" }
Type "it" for more

Projections

Find method provides the second field to do the projection work.

db.collection.find(, )

  • exclude
    - {attribute: 0}
  • include
    - {attribute: 1}

0 or 1 represents if this field should be excluded or included

Projections can help limit the fields, thereby improving the performances and reducing the cost.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Cluster0-shard-0:PRIMARY> db.movies.find({genre:"Action, Adventure"},{title:1})
{ "_id" : ObjectId("58c59c6a99d4ee0af9e0d117"), "title" : "Who Will Marry Mary?" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0d9c2"), "title" : "The New Exploits of Elaine" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0db62"), "title" : "The Ventures of Marguerite" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0dde5"), "title" : "The Iron Claw" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0dc25"), "title" : "Beatrice Fairfax" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0e28d"), "title" : "The Great Secret" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0e482"), "title" : "The Seven Pearls" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0e5f3"), "title" : "The Brass Bullet" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0e459"), "title" : "The Red Ace" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0e977"), "title" : "Wolves of Kultur" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0e8f3"), "title" : "Tarzan of the Apes" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0e71f"), "title" : "The Iron Test" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0e884"), "title" : "The Romance of Tarzan" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0ec74"), "title" : "Perils of Thunder Mountain" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0ea8d"), "title" : "The Fatal Fortune" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0f083"), "title" : "The Revenge of Tarzan" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0efa9"), "title" : "The Lost City" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0f0b7"), "title" : "The Screaming Shadow" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0f0cf"), "title" : "The Son of Tarzan" }
{ "_id" : ObjectId("58c59c6b99d4ee0af9e0f1a1"), "title" : "The Adventures of Tarzan" }
Type "it" for more

Updating Documents

updateOne()

1
2
3
4
5
6
7
8
9
10
db.collection.updateOne(
<filter>,
<update>,
{
upsert: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ]
}
)

Example

1
2
3
4
5
6
7
8
9
10
db.movieDetails.updateOne(
{
title: "The Martian"
},
{
$set: {
poster: "http//ia.media-imdb.com.images/M/MV5BMTc2MTQ3MDA1Nl5BanBnXkFtZTgwODA3OTI4NjE@._V1_SX300.jpg"
}
}
);

Update Operators

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.

updateMany()

1
2
3
4
5
6
7
8
9
10
db.collection.updateMany(
<filter>,
<update>,
{
upsert: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ]
}
)

upsert

findOne.

1
db.collection.findOne(query, projection)

replaceOne

1
2
3
4
5
6
7
8
9
db.collection.replaceOne(
<filter>,
<replacement>,
{
upsert: <boolean>,
writeConcern: <document>,
collation: <document>
}
)

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// find the document
detailDoc = db.moivesDetails.findOne({"imdb.id": "tt4368814"});

detailDoc.poster;

detailDoc.poster = "http://www.imdb.com/title/tt4368814/mediaviewer/rm2926634240"

detailDoc.genres;

detailDoc.genres.push("Documentary");

// replace a new one
db.movieDetails.replaceOne(
{
"imdb.id": detailDoc.imdb.id
},
detailDoc
);

Deleting Documents

deleteOne

1
2
3
4
5
6
7
db.collection.deleteOne(
<filter>,
{
writeConcern: <document>,
collation: <document>
}
)

deleteMany

1
2
3
4
5
6
7
db.collection.deleteMany(
<filter>,
{
writeConcern: <document>,
collation: <document>
}
)

Chapter03 Deeper Dive on the MongoDB Query Language

Introduction to Query Operators

Query Operators on CRUD

Comparison Operation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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:

1
2
3
MongoDB Enterprise > db.movieDetails.find( {writers: { $in : ["Ethan Coen", "Joel Coen"] }} ).count()
3
MongoDB Enterprise >

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.

use video

db.movieDetails.find({writers: {$in: ["Ethan Coen", "Joel Coen"]}}).count()

Element Operators

local db

1
2
3
4
5
6
7
MongoDB Enterprise > db.movieDetails.find({mpaaRating: {$exists: false}}).count()
2295
MongoDB Enterprise > db.movieDetails.find({mpaaRating: {$exists: true}}).count()
0
MongoDB Enterprise > db.movieDetails.find({mpaaRating: {$exists: null}}).count()
2295
MongoDB Enterprise >

remote db

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
➜  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.

1
2
3
Cluster0-shard-0:PRIMARY> db.data.find({atmosphericPressureChange: {$exists: false}}).count()
40668
Cluster0-shard-0:PRIMARY>

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({atmosphericPressureChange: {$exists: false}}).count()

In Compass, navigate to the 100YWeatherSmall.data collection and then apply the following filter in either the Schema or Documents view.

{atmosphericPressureChange: {$exists: false}}

Logical Operators

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
MongoDB Enterprise > db.movieDetails.find({$or: [{"tomato.meter": {$gt: 95}},{"metacritic": {$gt: 88}}]},{_id: 0, title: 1, "tomato.meter": 1, "metacritic": 1})
{ "title" : "Ai Weiwei: Never Sorry", "tomato" : { "meter" : 97 }, "metacritic" : 81 }
{ "title" : "E.T. the Extra-Terrestrial", "tomato" : { "meter" : 98 }, "metacritic" : 94 }
{ "title" : "Touchez Pas au Grisbi", "tomato" : { "meter" : 100 }, "metacritic" : 85 }
{ "title" : "Once Upon a Time in the West", "tomato" : { "meter" : 98 }, "metacritic" : 80 }
{ "title" : "Star Wars: Episode IV - A New Hope", "tomato" : { "meter" : 94 }, "metacritic" : 92 }
{ "title" : "Dr. Strangelove or: How I Learned to Stop Worrying and Love the Bomb", "tomato" : { "meter" : 99 }, "metacritic" : 96 }
{ "title" : "The Truman Show", "tomato" : { "meter" : 94 }, "metacritic" : 90 }
{ "title" : "Groundhog Day", "tomato" : { "meter" : 96 }, "metacritic" : 72 }
{ "title" : "The Night of the Hunter", "tomato" : { "meter" : 98 }, "metacritic" : 99 }
{ "title" : "Toy Story", "tomato" : { "meter" : 100 }, "metacritic" : 92 }
{ "title" : "Toy Story 3", "tomato" : { "meter" : 99 }, "metacritic" : 92 }
{ "title" : "The Straight Story", "tomato" : { "meter" : 96 }, "metacritic" : 86 }
{ "title" : "2001: A Space Odyssey", "tomato" : { "meter" : 96 }, "metacritic" : 86 }
{ "title" : "The Adventures of Robin Hood", "tomato" : { "meter" : 100 }, "metacritic" : 97 }
{ "title" : "Quiz Show", "tomato" : { "meter" : 96 }, "metacritic" : 88 }
{ "title" : "Evil Dead II", "tomato" : { "meter" : 98 }, "metacritic" : 69 }
{ "title" : "Alien", "tomato" : { "meter" : 97 }, "metacritic" : 83 }
{ "title" : "The Kid with a Bike", "tomato" : { "meter" : 96 }, "metacritic" : 87 }
{ "title" : "Drugstore Cowboy", "tomato" : { "meter" : 100 }, "metacritic" : 82 }
{ "title" : "Toy Story 3", "tomato" : { "meter" : 99 }, "metacritic" : 92 }
Type "it" for more
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
MongoDB Enterprise > db.movieDetails.find({$and: [{"tomato.meter": {$gt: 95}},{"metacritic": {$gt: 88}}]},{_id: 0, title: 1, "tomato.meter": 1, "metacritic": 1})
{ "title" : "E.T. the Extra-Terrestrial", "tomato" : { "meter" : 98 }, "metacritic" : 94 }
{ "title" : "Dr. Strangelove or: How I Learned to Stop Worrying and Love the Bomb", "tomato" : { "meter" : 99 }, "metacritic" : 96 }
{ "title" : "The Night of the Hunter", "tomato" : { "meter" : 98 }, "metacritic" : 99 }
{ "title" : "Toy Story", "tomato" : { "meter" : 100 }, "metacritic" : 92 }
{ "title" : "Toy Story 3", "tomato" : { "meter" : 99 }, "metacritic" : 92 }
{ "title" : "The Adventures of Robin Hood", "tomato" : { "meter" : 100 }, "metacritic" : 97 }
{ "title" : "Toy Story 3", "tomato" : { "meter" : 99 }, "metacritic" : 92 }
{ "title" : "Raiders of the Lost Ark", "tomato" : { "meter" : 96 }, "metacritic" : 90 }
{ "title" : "The Wizard of Oz", "tomato" : { "meter" : 99 }, "metacritic" : 100 }
{ "title" : "L.A. Confidential", "tomato" : { "meter" : 99 }, "metacritic" : 90 }
{ "title" : "La Dolce Vita", "tomato" : { "meter" : 96 }, "metacritic" : 93 }
{ "title" : "Au Hasard Balthazar", "tomato" : { "meter" : 100 }, "metacritic" : 100 }
MongoDB Enterprise > db.movieDetails.find({"tomato.meter": {$gt: 95},"metacritic": {$gt: 88}},{_id: 0, title: 1, "tomato.meter": 1, "metacritic": 1})
{ "title" : "E.T. the Extra-Terrestrial", "tomato" : { "meter" : 98 }, "metacritic" : 94 }
{ "title" : "Dr. Strangelove or: How I Learned to Stop Worrying and Love the Bomb", "tomato" : { "meter" : 99 }, "metacritic" : 96 }
{ "title" : "The Night of the Hunter", "tomato" : { "meter" : 98 }, "metacritic" : 99 }
{ "title" : "Toy Story", "tomato" : { "meter" : 100 }, "metacritic" : 92 }
{ "title" : "Toy Story 3", "tomato" : { "meter" : 99 }, "metacritic" : 92 }
{ "title" : "The Adventures of Robin Hood", "tomato" : { "meter" : 100 }, "metacritic" : 97 }
{ "title" : "Toy Story 3", "tomato" : { "meter" : 99 }, "metacritic" : 92 }
{ "title" : "Raiders of the Lost Ark", "tomato" : { "meter" : 96 }, "metacritic" : 90 }
{ "title" : "The Wizard of Oz", "tomato" : { "meter" : 99 }, "metacritic" : 100 }
{ "title" : "L.A. Confidential", "tomato" : { "meter" : 99 }, "metacritic" : 90 }
{ "title" : "La Dolce Vita", "tomato" : { "meter" : 96 }, "metacritic" : 93 }
{ "title" : "Au Hasard Balthazar", "tomato" : { "meter" : 100 }, "metacritic" : 100 }

Quiz

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:

1
2
3
Cluster0-shard-0:PRIMARY> db.shipwrecks.find( { $or : [{watlev : "always dry"}, {depth : 0}] } ).count()
2331
Cluster0-shard-0:PRIMARY>

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 ships

db.shipwrecks.find({$or: [{depth: 0}, {watlev: "always dry"}]}).count()

In Compass, navigate to the ships.shipwrecks collection and then apply the following filter in either the Schema or Documents view.

{$or: [{depth: 0}, {watlev: "always dry"}]}

Array Operators: $all $size $elemMatch

$all

1
2
3
MongoDB Enterprise > db.movieDetails.find({genres: {$all : ["Comedy", "Crime", "Drama"]}}).count()
8
MongoDB Enterprise >

Quiz

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:

1
2
3
Cluster0-shard-0:PRIMARY> db.data.find({sections : {$all: ["AG1", "MD1", "OA1"]}}).count()
10200
Cluster0-shard-0:PRIMARY>

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.

{sections: {$all: ["AG1", "MD1", "OA1"]}}

$size

1
2
3
MongoDB Enterprise > db.movieDetails.find({countries: {$size: 1}}).count()
1915
MongoDB Enterprise >

Quiz

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:

1
2
3
Cluster0-shard-0:PRIMARY> db.data.find({sections: {$size: 2}}).count()
2656
Cluster0-shard-0:PRIMARY>

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.

{sections: {$size: 2}}

$elemMatch

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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 } ]

db.movieDetails.find({"boxOffice.country": "Germany", "boxOffice.revenue": {$gt: 17}})
db.movieDetails.find({"boxOffice.country": "Germany", "boxOffice.revenue": {$gt: 228}})

use video
martian = db.movieDetails.findOne({title: "The Martian"})
martian
delete martian._id;
martian
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}
]
db.movieDetails.insertOne(martian);

db.movieDetails.find({boxOffice: {$elemMatch: {"country": "Germany", "revenue": {$gt: 17}}}})

db.movieDetails.find({boxOffice: {$elemMatch: {"country": "Germany", "revenue": {$gt: 16}}}})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
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”?

1
2
3
Cluster0-shard-0:PRIMARY> db.surveys.find({results: {$elemMatch: {score: 7, product: "abc"}}}).count()
124
Cluster0-shard-0:PRIMARY>

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.

{results: {$elemMatch: {product: "abc", score: 7}}}

Regex

1
2
3
MongoDB Enterprise > db.movieDetails.find({"awards.text": {$regex: /^Won.* /}}, {_id: 0, title: 1, "awards.text": 1}).pretty().count()
83
MongoDB Enterprise >

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.

{"_id": ObjectId("5964e8e5f0df64e7bc2d7373"), "results": [75, 88, 89]}

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?

1
2
3
Cluster0-shard-0:PRIMARY> db.scores.find({results: {$elemMatch: {$gte: 70, $lt: 80}}}).count()
744
Cluster0-shard-0:PRIMARY>

The answer is 744. 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.scores.find({results: {$elemMatch: {$gte: 70, $lt: 80}}}).count().

In Compass, navigate to the results.scores collection and then apply the following filter in either the Schema or Documents view.

{results: {$elemMatch: {$gte: 70, $lt: 80}}}


Reference

Learn MongoDB from MongoDB - M001: MongoDB Basics