@@ -6,24 +6,29 @@ Getting Started
66
77.. default-domain:: mongodb
88
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.
1321
1422.. _mongo-web-shell:
1523
16- Examples
17- --------
18-
1924.. include:: /includes/fact-mws.rst
2025
2126Click inside the shell to connect. Once connected, you can run the
2227examples in the shell above.
2328
2429.. tabs::
2530
26- .. tab:: Step 1
31+ .. tab:: 1. Switch Database
2732 :tabid: example-1
2833
2934 Switch Database
@@ -60,7 +65,7 @@ examples in the shell above.
6065
6166 To create a collection in the database, see the next tab.
6267
63- .. tab:: Step 2
68+ .. tab:: 2. Insert
6469 :tabid: example-2
6570
6671 Populate a Collection (Insert)
@@ -74,21 +79,75 @@ examples in the shell above.
7479
7580 The following example uses the
7681 :method:`db.collection.insertMany()` method to insert new
77- :doc:`documents </core/document>` into the ``inventory ``
82+ :doc:`documents </core/document>` into the ``movies ``
7883 collection. You can copy and paste the example into the
7984 :ref:`shell <mongo-web-shell>` above.
8085
8186 .. code-block:: javascript
8287
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+ ])
92151
93152 The operation returns a document that contains the
94153 acknowledgement indicator and an array that contains the
@@ -97,7 +156,7 @@ examples in the shell above.
97156 To verify the insert, you can query the collection (See the
98157 next tab).
99158
100- .. tab:: Step 3
159+ .. tab:: 3. Find All
101160 :tabid: example-3
102161
103162 Select All Documents
@@ -109,105 +168,62 @@ examples in the shell above.
109168 filter document <document-query-filter>` to the method.
110169
111170 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 ``
113172 collection.
114173
115174 .. code-block:: javascript
116175
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( { } )
127177
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
132179 :tabid: example-4
133180
134- Specify Equality Matches
135- ~~~~~~~~~~~~~~~~~~~~~~~~
181+ Filter Data with Comparison Operators
182+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
136183
137- For an equality match (i.e. ``<field>`` equals ``<value>``),
184+ For an equality match (``<field>`` equals ``<value>``),
138185 specify ``<field>: <value>`` in the :ref:`query filter
139186 document <document-query-filter>` and pass to the
140187 :method:`db.collection.find()` method.
141188
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``:
150192
151193 .. code-block:: javascript
152194
153- db.inventory .find( { status : "D " } );
195+ db.movies .find( { "directors" : "Christopher Nolan " } );
154196
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:
158199
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``:
166202
167203 .. code-block:: javascript
168204
169- db.inventory .find( { qty: 0, status: "D" } );
205+ db.movies .find( { "released": { $lt: ISODate("2000-01-01") } } );
170206
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:
174209
175210 .. code-block:: javascript
176211
177- db.inventory .find( { "size.uom ": "in" } )
212+ db.movies .find( { "awards.wins ": { $gt: 100 } } );
178213
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 ``:
182217
183218 .. code-block:: javascript
184219
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::
189223
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`
193225
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
211227 :tabid: example-5
212228
213229 Specify Fields to Return (Projection)
@@ -222,24 +238,68 @@ examples in the shell above.
222238
223239 - ``<field>: 0`` to exclude a field in the returned documents
224240
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:
228244
229245 .. code-block:: javascript
230246
231- db.inventory .find( { }, { item : 1, status : 1 } );
247+ db.movies .find( { }, { "title" : 1, "directors": 1, "year" : 1 } );
232248
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:
238254
239255 .. code-block:: javascript
240256
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
242280
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.
243303
244304Next Steps
245305----------
0 commit comments