Skip to content

DOCSP-48493: Databases & collections #1045

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

Merged
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
193 changes: 193 additions & 0 deletions source/databases-collections.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
.. _node-databases-collections:

=========================
Databases and Collections
=========================

.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: table, row, organize, storage, code example

Overview
--------

In this guide, you can learn how to interact with MongoDB databases and
collections by using the {+driver-short+}.

MongoDB organizes data into a hierarchy of the following levels:

- **Databases**: Top-level data structures in a MongoDB deployment that store collections.
- **Collections**: Groups of MongoDB documents. They are analogous to tables in relational databases.
- **Documents**: Units that store literal data such as strings, numbers, dates, and other embedded documents.
For more information about document field types and structure, see the
:manual:`Documents </core/document/>` entry in the {+mdb-server+} manual.

Access a Database
-----------------

You can access a database by calling the ``db()`` method on a
``MongoClient`` instance.

The following example accesses a database named ``"test_database"``:

.. literalinclude:: /includes/databases-collections.js
:start-after: start-access-database
:end-before: end-access-database
:language: javascript
:copyable:
:dedent:

Access a Collection
-------------------

You can access a collection by calling the ``collection()`` method on a ``Db``
instance.

The following example accesses a collection named ``"test_collection"``:

.. literalinclude:: /includes/databases-collections.js
:start-after: start-access-collection
:end-before: end-access-collection
:language: javascript
:copyable:
:dedent:

.. tip::

If the provided collection name does not already exist in the database,
MongoDB implicitly creates the collection when you first insert data
into it.

Create a Collection
-------------------

To explicitly create a collection, call the ``createCollection()`` method on
a ``Db`` instance.

The following example creates a collection named ``"example_collection"``:

.. literalinclude:: /includes/databases-collections.js
:start-after: start-create-collection
:end-before: end-create-collection
:language: javascript
:copyable:
:dedent:

You can specify collection options, such as maximum size and document
validation rules, by passing a ``CreateCollectionOptions`` instance to the
``createCollection()`` method. For a full list of
optional parameters, see the :manual:`create command </reference/command/create>`
entry in the {+mdb-server+} manual.

Get a List of Collections
-------------------------

You can query for a list of collections in a database by calling the
``listCollections()`` method on a ``Db`` instance.

The following example lists all collections in a database:

.. io-code-block::
:copyable:

.. input:: /includes/databases-collections.js
:language: javascript
:start-after: start-find-collections
:end-before: end-find-collections
:dedent:

.. output::
:language: console
:visible: false

{
name: 'example_collection',
type: 'collection',
options: {},
info: {
readOnly: false,
uuid: new UUID('...')
},
idIndex: { v: 2, key: { _id: 1 }, name: '_id_' }
}
{
name: 'test_collection',
type: 'collection',
options: {},
info: {
readOnly: false,
uuid: new UUID('...')
},
idIndex: { v: 2, key: { _id: 1 }, name: '_id_' }
}

To query for only the names of the collections in the database, pass
the ``nameOnly`` option to the ``listCollections()`` method and set its
value to ``true``, as shown in the following code:

.. io-code-block::
:copyable:

.. input:: /includes/databases-collections.js
:language: javascript
:start-after: start-find-collection-names
:end-before: end-find-collection-names
:dedent:

.. output::
:language: console
:visible: false

{ name: 'example_collection', type: 'collection' }
{ name: 'test_collection', type: 'collection' }

.. tip::

For more information about iterating over a cursor, see the :ref:`node-cursor`
guide.

Delete a Collection
-------------------

You can delete a collection by calling the ``drop()`` method on a
``Collection`` instance.

The following example deletes the ``"test_collection"`` collection:

.. literalinclude:: /includes/databases-collections.js
:start-after: start-delete-collection
:end-before: end-delete-collection
:language: javascript
:copyable:
:dedent:

.. warning:: Dropping a Collection Deletes All Data in the Collection

Dropping a collection from your database permanently deletes all
documents and all indexes within that collection.

Drop a collection only if the data in it is no longer needed.

API Documentation
-----------------

To learn more about any of the types or methods discussed in this
guide, see the following API documentation:

- `MongoClient <{+api+}/classes/MongoClient.html>`__
- `Db <{+api+}/classes/Db.html>`__
- `Collection <{+api+}/classes/Collection.html>`__
- `db() <{+api+}/classes/MongoClient.html#db>`__
- `collection() <{+api+}/classes/Db.html#collection>`__
- `createCollection() <{+api+}/classes/Db.html#createCollection>`__
- `listCollections() <{+api+}/classes/Db.html#listCollections>`__
- `dropCollection() <{+api+}/classes/Db.html#dropCollection>`__
50 changes: 50 additions & 0 deletions source/includes/databases-collections.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
const { MongoClient } = require("mongodb");

// Replace the placeholder with your connection string.
const uri = "<connection string>";
const client = new MongoClient(uri);

async function run() {
try {
// Accesses the test_database database
// start-access-database
const database = client.db("test_database");
// end-access-database

// Accesses the test_collection collection
// start-access-collection
const collection = database.collection("test_collection");
// end-access-collection

// Explicitly creates a collection in the database
// start-create-collection
const createColl = await database.createCollection("example_collection");
// end-create-collection

// Retrieves information about each collection in the database
// start-find-collections
const colls = database.listCollections();
for await (const doc of colls) {
console.log(doc)
}
// end-find-collections

// Retrieves the name of each collection in the database
// start-find-collection-names
const names = database.listCollections({}, { nameOnly: true });
for await (const doc of names) {
console.log(doc)
}
// end-find-collection-names

// Deletes the test_collection collection
// start-delete-collection
const collectionToDelete = database.collection("test_collection");
await collectionToDelete.drop();
// end-delete-collection
} finally {
await client.close();
}
}

run().catch(console.dir);
7 changes: 7 additions & 0 deletions source/index.txt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ MongoDB Node Driver

Get Started <get-started>
Connect </connect>
Databases & Collections </databases-collections>
CRUD Operations </crud>
Aggregation </aggregation>
Data Formats </data-formats>
Expand Down Expand Up @@ -59,6 +60,12 @@ Connect to MongoDB
Learn how to create and configure a connection to a MongoDB deployment in the
:ref:`<node-connect>` section.

Databases and Collections
-------------------------

Learn how to interact wth MongoDB databases and collections in the
:ref:`<node-databases-collections>` section.

Read and Write Data
-------------------

Expand Down
Loading