Menu
Share on

Introduction

MongoDB uses document-oriented structures to store, manage, and process data. Individual documents are organized into collections, which in turn, are stored in databases. Because the schema of each document is not defined by a static schema, document based systems offer more flexibility than relational systems that are composed of tables and records.

In this guide, we'll talk about how to create and manage the structures that MongoDB uses to organize data. We'll cover how to create and manage databases and then how to make collections to hold similar or related documents.

RELATED ON PRISMA.IO

If you are using Prisma Client with MongoDB, you can use the MongoDB connector (currently in preview) to connect and manage your data.

How to view existing databases

Before we begin creating new databases, it's helpful to get familiar with some of the methods that MongoDB provides for finding information about existing databases. This can help you understand the current state of the system before you begin making changes.

To display all of the databases on the system that you have access to, use the show dbs method:

show dbs
admin 0.000GB
config 0.000GB
local 0.000GB

MongoDB will respond with the names of all of the accessible databases on the system as well as a summary of their current storage space.

To see which database you are currently set to operate on, use the db.getName() command or its shorthand alias, db:

db
test

You may find that you are currently using a database that wasn't listed by the show dbs command. This is because in MongoDB, until you write the first document to the database, the database is not actually created. So, in the example output above, the shell is prepared to operate on a test database, but since it does not exist yet, it will not be returned by the show dbs command.

To switch to a different database, you can use the use command:

use admin
switched to db admin

To get some basic information about your current database, you can use the db.stats() method:

db.stats()
{
"db" : "admin",
"collections" : 3,
"views" : 0,
"objects" : 4,
"avgObjSize" : 278.25,
"dataSize" : 1113,
"storageSize" : 86016,
"indexes" : 5,
"indexSize" : 147456,
"totalSize" : 233472,
"scaleFactor" : 1,
"fsUsedSize" : 2876923904,
"fsTotalSize" : 25832407040,
"ok" : 1
}

The output shows information about the number of collections within the database, storage statistics, index information, and more.

How to create databases

MongoDB does not have an explicit command for creating a new database. Instead, as mentioned earlier, you have to instead indicate to MongoDB that you want to write new documents to a new database. When those documents are created, they will implicitly create the database.

To prepare MongoDB to write to a new database, issue the use command to switch to a non-existent database.

Here, we will set up MongoDB to create a new database called playground:

use playground
switched to db playground

If you check your current database, it will confirm that the playground database is currently the target of database-related commands:

db
playground

However, as mentioned before, since we have not yet created any documents, the database itself has not been created yet:

show dbs
admin 0.000GB
config 0.000GB
local 0.000GB

To actually create the new database, we will need to create something first.

How to view the collections in a database

In MongoDB, collections are structures used to group documents together using whatever system of categorization you want to implement. They live inside databases and store documents.

You can see the available collections in the database you're currently using by using the show collections method.

Here, we'll switch to the admin database that has some collections available to demonstrate:

use admin
show collections
system.roles
system.users
system.version

Alternatively, you can retrieve the same collection names in an array using the db.getCollectionNames() method:

db.getCollectionNames()
[ "system.roles", "system.users", "system.version" ]

To show additional information about the collections in the current database, use the db.getCollectionInfos() method:

db.getCollectionInfos()
[
{
"name" : "system.roles",
"type" : "collection",
"options" : {
},
"info" : {
"readOnly" : false,
"uuid" : UUID("776b1fd7-6014-4191-b33c-21350b590627")
},
"idIndex" : {
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
}
},
{
"name" : "system.users",
"type" : "collection",
"options" : {
},
"info" : {
"readOnly" : false,
"uuid" : UUID("8c824fd1-2150-4413-8fac-0b77d16505e5")
},
"idIndex" : {
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
}
},
{
"name" : "system.version",
"type" : "collection",
"options" : {
},
"info" : {
"readOnly" : false,
"uuid" : UUID("7501483a-45cc-492e-a1fd-ccb4349650cb")
},
"idIndex" : {
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
}
}
]

You can also optionally pass in a document to the command to filter the results. For example, if you are only interested in seeing the information about the system.version collection, you could type:

db.getCollectionInfos(
{
name: "system.version"
}
)
[
{
"name" : "system.version",
"type" : "collection",
"options" : {
},
"info" : {
"readOnly" : false,
"uuid" : UUID("7501483a-45cc-492e-a1fd-ccb4349650cb")
},
"idIndex" : {
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
}
}
]

To check how many documents a collection contains, use the db.<collection>.count() method. For instance, the following command checks how many documents are in the system.users collection:

db.system.users.count()
2

To view basic statistics about the collections in the current database, use the db.printCollectionStats() method:

db.printCollectionStats()

The command may output more information than you can easily consume, but contains, but is helpful in some scenarios where you need to take a deep look at the characteristics of a collection.

How to create collections

To create a new collection, there are two options: you can create collections either implicitly or explicitly.

As with databases, MongoDB can automatically create collections the first time a document is written to them. This method tells MongoDB to create a new collection by inserting a document into a collection that does not exist yet.

For instance, we can change back to the playground database that we were interested in earlier. Once we are in that namespace, we can insert a new document into a collection by calling the insert.() command on the name we'd like to use for the new collection. Here, we can create a document about a slide in a new collection called equipment:

use playground
db.equipment.insert({name: "slide"})
switched to db playground
WriteResult({ "nInserted" : 1 })

The output indicates that one document was written. The above command performed three separate actions. First, MongoDB created the playground database that we'd referenced in our use command. It also created the equipment collection within the database since we call the insert() command on that collection name. Finally, it creates the actual document within the equipment collection using the input we provided to the insert() command.

You can verify that all of these actions have been performed with the following commands:

show dbs
show collections
db.equipment.count()
db.equipment.find()

The output should show that the playground database is now among the listed databases, that the equipment collection is listed, that there is one document within the equipement collection, and that the document is the {name: "slide"} document we inserted in the command.

The other option to use to create collections is to explicitly use the db.createCollection() method. This allows you to create collections without adding any documents to them.

For example, you can create a new collection in the playground database called maintenance.requests by typing:

db.createCollection("maintenance.requests")
{ "ok" : 1 }

We can verify that the new collection shows up when we query for it, but that it has no documents:

show collections
db.maintenance.requests.count()
equipment
maintenance.requests
0

The db.createCollection() method is primarily useful because it allows you to specify various options upon creation. For example, we may want to create a create a capped collection, which is a collection that maintains an upper limit on its allocated size it stores by deleting its oldest document when full.

To create a capped collection called notifications that can store, at most, 10240 bytes of information, you could call:

db.createCollection(
"notifications",
{
capped: true,
size: 10240
}
)
{ "ok" : 1}

This will create a capped notification collection, which we can verify by typing:

db.getCollecitonInfos({"options.capped": true})
[
{
"name" : "notifications",
"type" : "collection",
"options" : {
"capped" : true,
"size" : 10240
},
"info" : {
"readOnly" : false,
"uuid" : UUID("dff7bfb0-1cfc-4170-ba60-fbb834ac6925")
},
"idIndex" : {
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
}
}
]

How to delete collections

To delete a collection, you can use the drop() method on the collection itself.

For example, to drop the capped notifications collection we created, you can type:

db.notifications.drop()
true

You can verify that the operation was successful by listing the collections in the current database again:

show collections
equipment
maintenance.requests

How to delete databases

To delete a whole database, call the db.dropDatabase() command. This will delete the current database, so be sure you are on the correct database before executing:

use playground
db.dropDatabase()
switched to db playground
{ "dropped" : "playground", "ok" : 1 }

If you check the list of available databases, playground is no longer displayed:

show dbs
admin 0.000GB
config 0.000GB
local 0.000GB

Since we haven't switched to a new database yet, MongoDB is still set up to create a playground database should we choose to add a new collection or document. You can verify this with the db command:

db
playground

Conclusion

Creating and managing databases and collections is an important skill when using MongoDB. These basic organizational tools allow you to group related documents together, query subsets of information, and set up authorization policies for different types of data. Getting familiar with how to effectively manage these structures will allow you to manage your data more effectively with fewer surprises.

RELATED ON PRISMA.IO

If you are using Prisma Client with MongoDB, you can use the MongoDB connector (currently in preview) to connect and manage your data.