@@ -6,24 +6,29 @@ Getting Started
6
6
7
7
.. default-domain:: mongodb
8
8
9
-
10
- The following page provides various examples for querying in the
11
- MongoDB Shell. For examples using MongoDB drivers, refer to the links
12
- in the :ref:`gs-additional-examples` section.
9
+ This tutorial walks you through inserting test data into a MongoDB
10
+ database and querying that data using the documentation's embedded
11
+ web shell. You do not need to deploy or install MongoDB to complete
12
+ this tutorial.
13
+
14
+ The examples in this tutorial use a subset of the
15
+ :atlas:`Sample Mflix Dataset </sample-data/sample-mflix/>`, which is
16
+ part of the sample data included in MongoDB's cloud-hosted service,
17
+ `MongoDB Atlas <https://www.mongodb.com/cloud/atlas?tck=docs_server>`__.
18
+ Atlas requires no installation overhead and offers a free tier to get
19
+ started. After completing this tutorial, you can use Atlas to
20
+ explore additional sample data or host your own data.
13
21
14
22
.. _mongo-web-shell:
15
23
16
- Examples
17
- --------
18
-
19
24
.. include:: /includes/fact-mws.rst
20
25
21
26
Click inside the shell to connect. Once connected, you can run the
22
27
examples in the shell above.
23
28
24
29
.. tabs::
25
30
26
- .. tab:: Step 1
31
+ .. tab:: 1. Switch Database
27
32
:tabid: example-1
28
33
29
34
Switch Database
@@ -60,7 +65,7 @@ examples in the shell above.
60
65
61
66
To create a collection in the database, see the next tab.
62
67
63
- .. tab:: Step 2
68
+ .. tab:: 2. Insert
64
69
:tabid: example-2
65
70
66
71
Populate a Collection (Insert)
@@ -74,21 +79,75 @@ examples in the shell above.
74
79
75
80
The following example uses the
76
81
:method:`db.collection.insertMany()` method to insert new
77
- :doc:`documents </core/document>` into the ``inventory ``
82
+ :doc:`documents </core/document>` into the ``movies ``
78
83
collection. You can copy and paste the example into the
79
84
:ref:`shell <mongo-web-shell>` above.
80
85
81
86
.. code-block:: javascript
82
87
83
- db.inventory.insertMany([
84
- { item: "journal", qty: 25, status: "A", size: { h: 14, w: 21, uom: "cm" }, tags: [ "blank", "red" ] },
85
- { item: "notebook", qty: 50, status: "A", size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank" ] },
86
- { item: "paper", qty: 10, status: "D", size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank", "plain" ] },
87
- { item: "planner", qty: 0, status: "D", size: { h: 22.85, w: 30, uom: "cm" }, tags: [ "blank", "red" ] },
88
- { item: "postcard", qty: 45, status: "A", size: { h: 10, w: 15.25, uom: "cm" }, tags: [ "blue" ] }
89
- ]);
90
-
91
- // MongoDB adds an _id field with an ObjectId value if the field is not present in the document
88
+ db.movies.insertMany([
89
+ {
90
+ title: 'Titanic',
91
+ year: 1997,
92
+ genres: [ 'Drama', 'Romance' ],
93
+ rated: 'PG-13',
94
+ languages: [ 'English', 'French', 'German', 'Swedish', 'Italian', 'Russian' ],
95
+ released: ISODate("1997-12-19T00:00:00.000Z"),
96
+ awards: {
97
+ wins: 127,
98
+ nominations: 63,
99
+ text: 'Won 11 Oscars. Another 116 wins & 63 nominations.'
100
+ },
101
+ cast: [ 'Leonardo DiCaprio', 'Kate Winslet', 'Billy Zane', 'Kathy Bates' ],
102
+ directors: [ 'James Cameron' ]
103
+ },
104
+ {
105
+ title: 'The Dark Knight',
106
+ year: 2008,
107
+ genres: [ 'Action', 'Crime', 'Drama' ],
108
+ rated: 'PG-13',
109
+ languages: [ 'English', 'Mandarin' ],
110
+ released: ISODate("2008-07-18T00:00:00.000Z"),
111
+ awards: {
112
+ wins: 144,
113
+ nominations: 106,
114
+ text: 'Won 2 Oscars. Another 142 wins & 106 nominations.'
115
+ },
116
+ cast: [ 'Christian Bale', 'Heath Ledger', 'Aaron Eckhart', 'Michael Caine' ],
117
+ directors: [ 'Christopher Nolan' ]
118
+ },
119
+ {
120
+ title: 'Spirited Away',
121
+ year: 2001,
122
+ genres: [ 'Animation', 'Adventure', 'Family' ],
123
+ rated: 'PG',
124
+ languages: [ 'Japanese' ],
125
+ released: ISODate("2003-03-28T00:00:00.000Z"),
126
+ awards: {
127
+ wins: 52,
128
+ nominations: 22,
129
+ text: 'Won 1 Oscar. Another 51 wins & 22 nominations.'
130
+ },
131
+ cast: [ 'Rumi Hiiragi', 'Miyu Irino', 'Mari Natsuki', 'Takashi Naitè' ],
132
+ directors: [ 'Hayao Miyazaki' ]
133
+ },
134
+ {
135
+ title: 'Casablanca',
136
+ genres: [ 'Drama', 'Romance', 'War' ],
137
+ rated: 'PG',
138
+ cast: [ 'Humphrey Bogart', 'Ingrid Bergman', 'Paul Henreid', 'Claude Rains' ],
139
+ languages: [ 'English', 'French', 'German', 'Italian' ],
140
+ released: ISODate("1943-01-23T00:00:00.000Z"),
141
+ directors: [ 'Michael Curtiz' ],
142
+ awards: {
143
+ wins: 9,
144
+ nominations: 6,
145
+ text: 'Won 3 Oscars. Another 6 wins & 6 nominations.'
146
+ },
147
+ lastupdated: '2015-09-04 00:22:54.600000000',
148
+ year: 1942
149
+ }
150
+ ])
92
151
93
152
The operation returns a document that contains the
94
153
acknowledgement indicator and an array that contains the
@@ -97,7 +156,7 @@ examples in the shell above.
97
156
To verify the insert, you can query the collection (See the
98
157
next tab).
99
158
100
- .. tab:: Step 3
159
+ .. tab:: 3. Find All
101
160
:tabid: example-3
102
161
103
162
Select All Documents
@@ -109,105 +168,62 @@ examples in the shell above.
109
168
filter document <document-query-filter>` to the method.
110
169
111
170
In the :ref:`shell <mongo-web-shell>`, copy and paste the
112
- following to return all documents in the ``inventory ``
171
+ following to return all documents in the ``movies ``
113
172
collection.
114
173
115
174
.. code-block:: javascript
116
175
117
- db.inventory.find({})
118
-
119
- To format the results, append the ``.pretty()`` to the
120
- ``find`` operation:
121
-
122
- .. code-block:: javascript
123
-
124
- db.inventory.find({}).pretty()
125
-
126
- .. note::
176
+ db.movies.find( { } )
127
177
128
- The example assumes that you have populated the
129
- ``inventory`` collection from the previous step.
130
-
131
- .. tab:: Step 4
178
+ .. tab:: 4. Filter Data
132
179
:tabid: example-4
133
180
134
- Specify Equality Matches
135
- ~~~~~~~~~~~~~~~~~~~~~~~~
181
+ Filter Data with Comparison Operators
182
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
136
183
137
- For an equality match (i.e. ``<field>`` equals ``<value>``),
184
+ For an equality match (``<field>`` equals ``<value>``),
138
185
specify ``<field>: <value>`` in the :ref:`query filter
139
186
document <document-query-filter>` and pass to the
140
187
:method:`db.collection.find()` method.
141
188
142
- .. note::
143
-
144
- The examples assume that you have populated the
145
- ``inventory`` collection.
146
-
147
- - In the :ref:`shell <mongo-web-shell>`, copy and paste the
148
- following to return documents where ``status`` field equals
149
- ``"D"``:
189
+ - In the :ref:`shell <mongo-web-shell>`, run the following
190
+ query to find movies that were directed by
191
+ ``Christopher Nolan``:
150
192
151
193
.. code-block:: javascript
152
194
153
- db.inventory .find( { status : "D " } );
195
+ db.movies .find( { "directors" : "Christopher Nolan " } );
154
196
155
- - In the :ref:`shell <mongo-web-shell>`, copy and paste the
156
- following to return document where ``qty`` field equals
157
- ``0``:
197
+ You can use :ref:`comparison operators <query-selectors-comparison>`
198
+ to perform more advanced queries:
158
199
159
- .. code-block:: javascript
160
-
161
- db.inventory.find( { qty: 0 } );
162
-
163
- - In the :ref:`shell <mongo-web-shell>`, copy and paste the
164
- following to return document where ``qty`` field equals
165
- ``0`` and ``status`` field equals ``"D"``:
200
+ - Run the following query to return movies that were released
201
+ before the year ``2000``:
166
202
167
203
.. code-block:: javascript
168
204
169
- db.inventory .find( { qty: 0, status: "D" } );
205
+ db.movies .find( { "released": { $lt: ISODate("2000-01-01") } } );
170
206
171
- - In the :ref:`shell <mongo-web-shell>`, copy and paste the
172
- following to return document where the ``uom`` field, nested
173
- inside the size document, equals ``"in"``:
207
+ - Run the following query to return movies that won more than
208
+ ``100`` awards:
174
209
175
210
.. code-block:: javascript
176
211
177
- db.inventory .find( { "size.uom ": "in" } )
212
+ db.movies .find( { "awards.wins ": { $gt: 100 } } );
178
213
179
- - In the :ref:`shell <mongo-web-shell>`, copy and paste the
180
- following to return document where the ``size `` field equals
181
- the document ``{ h: 14, w: 21, uom: "cm" } ``:
214
+ - Run the following query to return movies where the
215
+ ``languages`` array contains *either* ``Japanese `` or
216
+ ``Mandarin ``:
182
217
183
218
.. code-block:: javascript
184
219
185
- db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )
186
-
187
- Equality matches on the embedded document require an exact
188
- match, including the field order.
220
+ db.movies.find( { "languages": { $in: [ "Japanese", "Mandarin" ] } } )
221
+
222
+ .. seealso::
189
223
190
- - In the :ref:`shell <mongo-web-shell>`, copy and paste the
191
- following to return documents where the ``tags`` array
192
- contains ``"red"`` as one of its elements:
224
+ :ref:`query-projection-operators-top`
193
225
194
- .. code-block:: javascript
195
-
196
- db.inventory.find( { tags: "red" } )
197
-
198
- If the ``tags`` field is a string instead of an array, then
199
- the query is just an equality match.
200
-
201
- - In the :ref:`shell <mongo-web-shell>`, copy and paste the
202
- following to return documents where the ``tags`` field
203
- matches the specified array exactly, including the order:
204
-
205
- .. code-block:: javascript
206
-
207
- db.inventory.find( { tags: [ "red", "blank" ] } )
208
-
209
-
210
- .. tab:: Step 5
226
+ .. tab:: 5. Project Fields
211
227
:tabid: example-5
212
228
213
229
Specify Fields to Return (Projection)
@@ -222,24 +238,68 @@ examples in the shell above.
222
238
223
239
- ``<field>: 0`` to exclude a field in the returned documents
224
240
225
- In the :ref:`shell <mongo-web-shell>`, copy and paste the
226
- following to return the ``_id ``, ``item ``, and the ``status``
227
- fields from all documents in the ``inventory `` collection:
241
+ In the :ref:`shell <mongo-web-shell>`, run the following query to
242
+ return the ``id ``, ``title ``, ``directors``, and ``year`` fields
243
+ from all documents in the ``movies `` collection:
228
244
229
245
.. code-block:: javascript
230
246
231
- db.inventory .find( { }, { item : 1, status : 1 } );
247
+ db.movies .find( { }, { "title" : 1, "directors": 1, "year" : 1 } );
232
248
233
- You do not have to specify the ``_id`` field to return the
234
- field. It returns by default. To exclude the field, set it to
235
- ``0`` in the projection document. For example, copy and paste
236
- the following to return only the ``item ``, and the ``status``
237
- fields in the matching documents:
249
+ You do not have to specify the ``_id`` field to return the field.
250
+ It returns by default. To exclude the field, set it to ``0`` in
251
+ the projection document. For example, run the following query to
252
+ return only the ``title ``, and the ``genres`` fields in the
253
+ matching documents:
238
254
239
255
.. code-block:: javascript
240
256
241
- db.inventory.find( {}, { _id: 0, item: 1, status: 1 } );
257
+ db.movies.find( { }, { "_id": 0, "title": 1, "genres": 1 } );
258
+
259
+ .. tab:: 6. Aggregate
260
+ :tabid: example-6
261
+
262
+ Aggregate Data (:pipeline:`$group`)
263
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
264
+
265
+ You can use aggregation to group values from multiple documents
266
+ together and return a single result. Aggregation in MongoDB
267
+ is performed with an :ref:`aggregation pipeline
268
+ <aggregation-framework>`.
269
+
270
+ While :method:`find()` operations are useful for data
271
+ retrieval, the aggregation pipeline allows you to manipulate
272
+ data, perform calculations, and write more expressive queries
273
+ than simple :ref:`CRUD operations <crud>`.
274
+
275
+ In the :ref:`shell <mongo-web-shell>`, run the following
276
+ aggregation pipeline to count the number of occurrences
277
+ of each ``genre`` value:
278
+
279
+ .. code-block:: javascript
242
280
281
+ db.movies.aggregate( [
282
+ { $unwind: "$genres" },
283
+ {
284
+ $group: {
285
+ _id: "$genres",
286
+ genreCount: { $count: { } }
287
+ }
288
+ },
289
+ { $sort: { "genreCount": -1 } }
290
+ ] )
291
+
292
+ The pipeline uses:
293
+
294
+ - :pipeline:`$unwind` to output a document for each element
295
+ in the ``genres`` array.
296
+
297
+ - :pipeline:`$group` and the :group:`$count` accumulator
298
+ to count the number of occurrences of each ``genre``. This
299
+ value is stored in the ``genreCount`` field.
300
+
301
+ - :pipeline:`$sort` to sort the resulting documents
302
+ by the ``genreCount`` field in descending order.
243
303
244
304
Next Steps
245
305
----------
0 commit comments