Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(DOCSP-17930): Update getting started page for Atlas #5844

Merged
merged 1 commit into from
Sep 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions source/reference/operator/query.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
.. _query-projection-operators-top:

==============================
Query and Projection Operators
==============================
Expand Down
258 changes: 159 additions & 99 deletions source/tutorial/getting-started.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,29 @@ Getting Started

.. default-domain:: mongodb


The following page provides various examples for querying in the
MongoDB Shell. For examples using MongoDB drivers, refer to the links
in the :ref:`gs-additional-examples` section.
This tutorial walks you through inserting test data into a MongoDB
database and querying that data using the documentation's embedded
web shell. You do not need to deploy or install MongoDB to complete
this tutorial.

The examples in this tutorial use a subset of the
:atlas:`Sample Mflix Dataset </sample-data/sample-mflix/>`, which is
part of the sample data included in MongoDB's cloud-hosted service,
`MongoDB Atlas <https://www.mongodb.com/cloud/atlas?tck=docs_server>`__.
Atlas requires no installation overhead and offers a free tier to get
started. After completing this tutorial, you can use Atlas to
explore additional sample data or host your own data.

.. _mongo-web-shell:

Examples
--------

.. include:: /includes/fact-mws.rst

Click inside the shell to connect. Once connected, you can run the
examples in the shell above.

.. tabs::

.. tab:: Step 1
.. tab:: 1. Switch Database
:tabid: example-1

Switch Database
Expand Down Expand Up @@ -60,7 +65,7 @@ examples in the shell above.

To create a collection in the database, see the next tab.

.. tab:: Step 2
.. tab:: 2. Insert
:tabid: example-2

Populate a Collection (Insert)
Expand All @@ -74,21 +79,75 @@ examples in the shell above.

The following example uses the
:method:`db.collection.insertMany()` method to insert new
:doc:`documents </core/document>` into the ``inventory``
:doc:`documents </core/document>` into the ``movies``
collection. You can copy and paste the example into the
:ref:`shell <mongo-web-shell>` above.

.. code-block:: javascript

db.inventory.insertMany([
{ item: "journal", qty: 25, status: "A", size: { h: 14, w: 21, uom: "cm" }, tags: [ "blank", "red" ] },
{ item: "notebook", qty: 50, status: "A", size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank" ] },
{ item: "paper", qty: 10, status: "D", size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank", "plain" ] },
{ item: "planner", qty: 0, status: "D", size: { h: 22.85, w: 30, uom: "cm" }, tags: [ "blank", "red" ] },
{ item: "postcard", qty: 45, status: "A", size: { h: 10, w: 15.25, uom: "cm" }, tags: [ "blue" ] }
]);

// MongoDB adds an _id field with an ObjectId value if the field is not present in the document
db.movies.insertMany([
{
title: 'Titanic',
year: 1997,
genres: [ 'Drama', 'Romance' ],
rated: 'PG-13',
languages: [ 'English', 'French', 'German', 'Swedish', 'Italian', 'Russian' ],
released: ISODate("1997-12-19T00:00:00.000Z"),
awards: {
wins: 127,
nominations: 63,
text: 'Won 11 Oscars. Another 116 wins & 63 nominations.'
},
cast: [ 'Leonardo DiCaprio', 'Kate Winslet', 'Billy Zane', 'Kathy Bates' ],
directors: [ 'James Cameron' ]
},
{
title: 'The Dark Knight',
year: 2008,
genres: [ 'Action', 'Crime', 'Drama' ],
rated: 'PG-13',
languages: [ 'English', 'Mandarin' ],
released: ISODate("2008-07-18T00:00:00.000Z"),
awards: {
wins: 144,
nominations: 106,
text: 'Won 2 Oscars. Another 142 wins & 106 nominations.'
},
cast: [ 'Christian Bale', 'Heath Ledger', 'Aaron Eckhart', 'Michael Caine' ],
directors: [ 'Christopher Nolan' ]
},
{
title: 'Spirited Away',
year: 2001,
genres: [ 'Animation', 'Adventure', 'Family' ],
rated: 'PG',
languages: [ 'Japanese' ],
released: ISODate("2003-03-28T00:00:00.000Z"),
awards: {
wins: 52,
nominations: 22,
text: 'Won 1 Oscar. Another 51 wins & 22 nominations.'
},
cast: [ 'Rumi Hiiragi', 'Miyu Irino', 'Mari Natsuki', 'Takashi Naitè' ],
directors: [ 'Hayao Miyazaki' ]
},
{
title: 'Casablanca',
genres: [ 'Drama', 'Romance', 'War' ],
rated: 'PG',
cast: [ 'Humphrey Bogart', 'Ingrid Bergman', 'Paul Henreid', 'Claude Rains' ],
languages: [ 'English', 'French', 'German', 'Italian' ],
released: ISODate("1943-01-23T00:00:00.000Z"),
directors: [ 'Michael Curtiz' ],
awards: {
wins: 9,
nominations: 6,
text: 'Won 3 Oscars. Another 6 wins & 6 nominations.'
},
lastupdated: '2015-09-04 00:22:54.600000000',
year: 1942
}
])

The operation returns a document that contains the
acknowledgement indicator and an array that contains the
Expand All @@ -97,7 +156,7 @@ examples in the shell above.
To verify the insert, you can query the collection (See the
next tab).

.. tab:: Step 3
.. tab:: 3. Find All
:tabid: example-3

Select All Documents
Expand All @@ -109,105 +168,62 @@ examples in the shell above.
filter document <document-query-filter>` to the method.

In the :ref:`shell <mongo-web-shell>`, copy and paste the
following to return all documents in the ``inventory``
following to return all documents in the ``movies``
collection.

.. code-block:: javascript

db.inventory.find({})

To format the results, append the ``.pretty()`` to the
``find`` operation:

.. code-block:: javascript

db.inventory.find({}).pretty()

.. note::
db.movies.find( { } )

The example assumes that you have populated the
``inventory`` collection from the previous step.

.. tab:: Step 4
.. tab:: 4. Filter Data
:tabid: example-4

Specify Equality Matches
~~~~~~~~~~~~~~~~~~~~~~~~
Filter Data with Comparison Operators
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

For an equality match (i.e. ``<field>`` equals ``<value>``),
For an equality match (``<field>`` equals ``<value>``),
specify ``<field>: <value>`` in the :ref:`query filter
document <document-query-filter>` and pass to the
:method:`db.collection.find()` method.

.. note::

The examples assume that you have populated the
``inventory`` collection.

- In the :ref:`shell <mongo-web-shell>`, copy and paste the
following to return documents where ``status`` field equals
``"D"``:
- In the :ref:`shell <mongo-web-shell>`, run the following
query to find movies that were directed by
``Christopher Nolan``:

.. code-block:: javascript

db.inventory.find( { status: "D" } );
db.movies.find( { "directors": "Christopher Nolan" } );

- In the :ref:`shell <mongo-web-shell>`, copy and paste the
following to return document where ``qty`` field equals
``0``:
You can use :ref:`comparison operators <query-selectors-comparison>`
to perform more advanced queries:

.. code-block:: javascript

db.inventory.find( { qty: 0 } );

- In the :ref:`shell <mongo-web-shell>`, copy and paste the
following to return document where ``qty`` field equals
``0`` and ``status`` field equals ``"D"``:
- Run the following query to return movies that were released
before the year ``2000``:

.. code-block:: javascript

db.inventory.find( { qty: 0, status: "D" } );
db.movies.find( { "released": { $lt: ISODate("2000-01-01") } } );

- In the :ref:`shell <mongo-web-shell>`, copy and paste the
following to return document where the ``uom`` field, nested
inside the size document, equals ``"in"``:
- Run the following query to return movies that won more than
``100`` awards:

.. code-block:: javascript

db.inventory.find( { "size.uom": "in" } )
db.movies.find( { "awards.wins": { $gt: 100 } } );

- In the :ref:`shell <mongo-web-shell>`, copy and paste the
following to return document where the ``size`` field equals
the document ``{ h: 14, w: 21, uom: "cm" }``:
- Run the following query to return movies where the
``languages`` array contains *either* ``Japanese`` or
``Mandarin``:

.. code-block:: javascript

db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )

Equality matches on the embedded document require an exact
match, including the field order.
db.movies.find( { "languages": { $in: [ "Japanese", "Mandarin" ] } } )

.. seealso::

- In the :ref:`shell <mongo-web-shell>`, copy and paste the
following to return documents where the ``tags`` array
contains ``"red"`` as one of its elements:
:ref:`query-projection-operators-top`

.. code-block:: javascript

db.inventory.find( { tags: "red" } )

If the ``tags`` field is a string instead of an array, then
the query is just an equality match.

- In the :ref:`shell <mongo-web-shell>`, copy and paste the
following to return documents where the ``tags`` field
matches the specified array exactly, including the order:

.. code-block:: javascript

db.inventory.find( { tags: [ "red", "blank" ] } )


.. tab:: Step 5
.. tab:: 5. Project Fields
:tabid: example-5

Specify Fields to Return (Projection)
Expand All @@ -222,24 +238,68 @@ examples in the shell above.

- ``<field>: 0`` to exclude a field in the returned documents

In the :ref:`shell <mongo-web-shell>`, copy and paste the
following to return the ``_id``, ``item``, and the ``status``
fields from all documents in the ``inventory`` collection:
In the :ref:`shell <mongo-web-shell>`, run the following query to
return the ``id``, ``title``, ``directors``, and ``year`` fields
from all documents in the ``movies`` collection:

.. code-block:: javascript

db.inventory.find( { }, { item: 1, status: 1 } );
db.movies.find( { }, { "title": 1, "directors": 1, "year": 1 } );

You do not have to specify the ``_id`` field to return the
field. It returns by default. To exclude the field, set it to
``0`` in the projection document. For example, copy and paste
the following to return only the ``item``, and the ``status``
fields in the matching documents:
You do not have to specify the ``_id`` field to return the field.
It returns by default. To exclude the field, set it to ``0`` in
the projection document. For example, run the following query to
return only the ``title``, and the ``genres`` fields in the
matching documents:

.. code-block:: javascript

db.inventory.find( {}, { _id: 0, item: 1, status: 1 } );
db.movies.find( { }, { "_id": 0, "title": 1, "genres": 1 } );

.. tab:: 6. Aggregate
:tabid: example-6

Aggregate Data (:pipeline:`$group`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can use aggregation to group values from multiple documents
together and return a single result. Aggregation in MongoDB
is performed with an :ref:`aggregation pipeline
<aggregation-framework>`.

While :method:`find()` operations are useful for data
retrieval, the aggregation pipeline allows you to manipulate
data, perform calculations, and write more expressive queries
than simple :ref:`CRUD operations <crud>`.

In the :ref:`shell <mongo-web-shell>`, run the following
aggregation pipeline to count the number of occurrences
of each ``genre`` value:

.. code-block:: javascript

db.movies.aggregate( [
{ $unwind: "$genres" },
{
$group: {
_id: "$genres",
genreCount: { $count: { } }
}
},
{ $sort: { "genreCount": -1 } }
] )

The pipeline uses:

- :pipeline:`$unwind` to output a document for each element
in the ``genres`` array.

- :pipeline:`$group` and the :group:`$count` accumulator
to count the number of occurrences of each ``genre``. This
value is stored in the ``genreCount`` field.

- :pipeline:`$sort` to sort the resulting documents
by the ``genreCount`` field in descending order.

Next Steps
----------
Expand Down