How to create a MongoDB database: 6 critical aspects to know
MongoDB doesn't have a CREATE DATABASE command: a database comes to life the moment you store data in it.
Depending on what your software needs, you might prioritize flexibility, scalability, performance, or speed, which is why choosing a database can be confusing. If you need a flexible data model that maps naturally to the objects in your code, scales horizontally, and handles analytics with powerful aggregations, MongoDB may be the right fit.
In this article, we'll look at how a MongoDB database is structured, then create one, add data, manage users and roles, design documents for performance, monitor the database, and finally delete it. Every shell command in this article was tested with MongoDB 9.0 and the MongoDB Shell (mongosh) 2.14.
How is a MongoDB database structured?#
MongoDB is a document database, a type of NoSQL database. Instead of tables with a fixed set of columns, as in relational databases, it stores data as flexible documents, so you don't need to define a schema before you add data. A MongoDB server can hold many databases, each database holds collections, and each collection holds documents.
Below, we'll explore the key building blocks of MongoDB.
Documents#
A document is a single record, made of field-value pairs, much like a JSON object. Documents map naturally to the objects in your application code, which makes them straightforward to work with:
{
"name": "Chris",
"department": "Sales",
"skills": ["negotiation", "CRM"],
"address": { "city": "Lagos", "country": "Nigeria" }
}In a relational table, you have to add a column before any row can have a new field. In MongoDB, documents in the same collection can have different fields, and a field can hold arrays or other documents, which lets you represent hierarchical data in a single record.
MongoDB stores documents in BSON, a binary form of JSON. BSON is faster to parse and supports more data types than JSON, such as dates, 64-bit integers, decimals, and ObjectIds. A single document can be up to 16 MB.
Collections#
A collection is a group of documents in a database, similar to a table in a relational database. Collections are more flexible than tables, because documents in a collection don't have to share the same fields or types. If you want to enforce a structure, you can still add schema validation rules to a collection.
To list the collections in the current database, run show collections in the MongoDB Shell.
Indexes#
You can index any field in a document, including fields in embedded documents and arrays. With an index, MongoDB can find matching documents by scanning the index, instead of reading every document in the collection.
MongoDB supports several index types, including compound indexes on multiple fields. For example, if you often search for employees by last name and first name, a single index on both fields, { lastName: 1, firstName: 1 }, serves those queries better than two separate indexes.
Aggregation pipelines#
The aggregation pipeline processes documents through a series of stages, such as $match to filter, $group to summarize, $sort, and $lookup to join data from another collection. Each stage transforms the documents and passes the results to the next one, which makes pipelines a powerful way to analyze and reshape data inside the database.
Replica sets#
A replica set is a group of MongoDB servers that keep copies of the same data. One member, the primary, receives all writes, and the others, the secondaries, replicate them. If the primary fails, the members elect a new one, so the database stays available.
Replication isn't automatic for every MongoDB install. A local server you start yourself is a standalone server with a single copy of your data, unless you configure a replica set. MongoDB Atlas, MongoDB's cloud service, deploys every cluster, including free ones, as a three-member replica set.
Sharding#
Sharding distributes a collection's data across multiple servers, called shards, so a database can grow beyond the storage and throughput of a single machine. MongoDB splits the data by a shard key that you choose, and routes each query to the shards that hold the matching documents.
How to create a MongoDB database#
To create a database, you first need a MongoDB server and a way to connect to it. You can install MongoDB on your computer, run it in Docker, or use a hosted database in MongoDB Atlas.
To install MongoDB locally, follow the installation guide for your OS, or download MongoDB Community Server from the download page. Since MongoDB 6.0, the MongoDB Shell isn't included with the server, so also install mongosh. The old mongo shell has been removed.
If you have Docker, you can start a MongoDB server without installing it. The official image includes mongosh:
docker run -d --name mongodb -p 27017:27017 mongo:9To check your installation, print the versions of the server and the shell:
mongod --version
mongosh --versionUsing the MongoDB Shell#
Step 1: Start the server and open the shell
If you installed MongoDB locally, start the server. How you do it depends on your OS:
- Windows: The installer sets up MongoDB as a service that starts automatically. To start it manually, run
net start MongoDBin an administrator terminal. - macOS: If you installed MongoDB with Homebrew, run
brew services start mongodb-community. - Linux: On most distributions, run
sudo systemctl start mongod.
Then open the MongoDB Shell:
mongoshWithout arguments, mongosh connects to a server on localhost at the default port, 27017. To connect to another server, pass its connection string, for example, mongosh "mongodb+srv://cluster0.example.mongodb.net/" --username myuser for an Atlas cluster. With the Docker container above, you can also run docker exec -it mongodb mongosh.
In the shell, you can create databases, insert and edit data, run administrative commands, and delete data.
Step 2: Create your database
MongoDB doesn't have a CREATE DATABASE command: a database comes to life the moment you store data in it. Instead, the use command switches to a database, whether it exists or not:
use companyThe shell confirms the switch, and its prompt changes to the database name:
switched to db companyType db to see which database you're using. To list the databases on the server, run show dbs:
admin 100.00 KiB
config 12.00 KiB
local 40.00 KiBThe admin, config, and local databases are system databases that MongoDB creates and uses internally.
Notice that company isn't listed. MongoDB only creates the database when you add its first collection or document, which you'll do in the next section.
Using the Atlas UI#
You can also create a database in MongoDB Atlas, MongoDB's database service. Atlas offers free clusters that never expire, which are more than enough to create a database and try out MongoDB.
When you create a cluster, Atlas also asks you to create a database user and to add your IP address to the IP access list. You need both to connect to the cluster from the shell, Compass, or your application.
To create a database, open your project in Atlas and go to the Data Explorer page. Create a database there, entering its name and the name of its first collection. You can then insert documents in the Data Explorer, or connect to the database with mongosh, Compass, or a driver.
Using MongoDB Compass#
MongoDB Compass is a free graphical interface for MongoDB. It lets you browse and edit data, build queries and aggregations, view the schema of your collections, and analyze query performance, without writing shell commands. Download it from the Compass install page.
To create a database in Compass:
- Open Compass and create a connection. Paste your connection string, such as
mongodb://localhost:27017for a local server, and click Connect. - In the Connections sidebar, click the plus icon next to the connection name to open the Create Database dialog.
- Enter the name of the database and its first collection, then click Create Database.
To add documents, click the collection, then click Add Data > Insert Document. You can paste a single document, or several documents as an array:
[
{ "_id": 1, "item": { "name": "apple", "code": "123" }, "qty": 15, "tags": ["A", "B", "C"] },
{ "_id": 2, "item": { "name": "banana", "code": "123" }, "qty": 20, "tags": ["B"] },
{ "_id": 3, "item": { "name": "spinach", "code": "456" }, "qty": 25, "tags": ["A", "B"] }
]Click Insert to add them to the collection.
Managing your MongoDB database#
With your database in place, let's add data to it, then control who can access it with users and roles.
Working with collections and documents#
You don't need to create a collection before you use it. When you insert a document into a collection that doesn't exist, MongoDB creates the collection, and the database too if needed.
In the company database, insert a document into a new employees collection with insertOne():
db.employees.insertOne({ name: "Chris", department: "Sales" })MongoDB confirms the insert and returns the new document's ID:
{
acknowledged: true,
insertedId: ObjectId('6b0dbcb2ba1900cb247dcd13')
}Here, db is the current database, and employees is the new collection. You didn't set a primary key, because MongoDB adds an _id field to every document automatically, with a unique ObjectId as its value. To see the documents in the collection, use find():
db.employees.find()[
{
_id: ObjectId('6b0dbcb2ba1900cb247dcd13'),
name: 'Chris',
department: 'Sales'
}
]You can also set the _id value yourself, as long as it's unique in the collection:
db.employees.insertOne({ _id: 1, name: "Ava", department: "Public Relations" })If you try to insert another document with _id: 1, MongoDB rejects it with an E11000 duplicate key error.
To insert several documents at once, use insertMany() with an array of documents. Avoid the older insert() method you may see in older tutorials: it's deprecated, and mongosh prints a DeprecationWarning when you use it.
Now that the database has data, run show dbs again, and company is in the list:
admin 100.00 KiB
company 8.00 KiB
config 12.00 KiB
local 40.00 KiBIf you want to create an empty collection, for example, to set options or validation rules first, use db.createCollection("orders").
Managing users#
When you deploy MongoDB, you should turn on access control and give each application or person a user with only the permissions they need. In Atlas, access control is always on, and you can manage database users in the Atlas UI. On your own server, you manage them with these shell commands. To run them, you need a user with the userAdmin or userAdminAnyDatabase role, such as the admin user you create when you set up the server.
A user belongs to the database where you create it, called its authentication database. Most of the commands below have a shell helper, such as db.createUser(), and an equivalent database command, such as createUser, that you can run with db.runCommand().
createUser
db.createUser() creates a user in the current database. This creates a user called appUser in the products database that can read and write data in that database:
use products
db.createUser({
user: "appUser",
pwd: "changeMe123",
roles: ["readWrite"]
})MongoDB returns { ok: 1 }. If the user already exists, you get an error: User "appUser@products" already exists.
A role given by name, such as "readWrite", applies to the current database. To give a role on another database, use a document, such as { role: "read", db: "reporting" }. To avoid typing the password in your command history, use passwordPrompt() as the pwd value, and mongosh asks for it.
The new user can now connect with a connection string that includes the database:
mongosh "mongodb://appUser:changeMe123@localhost:27017/products"This user can insert and read documents in products, but reading from another database, such as company, fails with an Unauthorized error.
getUser and usersInfo
To see a user's details and roles, use db.getUser():
db.getUser("appUser"){
_id: 'products.appUser',
userId: UUID('d37f7315-cae2-4f96-a265-7ce185c7d4d6'),
user: 'appUser',
db: 'products',
roles: [ { role: 'readWrite', db: 'products' } ],
mechanisms: [ 'SCRAM-SHA-1', 'SCRAM-SHA-256' ]
}To list every user in the current database, use db.getUsers(). The usersInfo command does the same and accepts more options, such as showPrivileges: true to include the user's privileges. For example, this returns the users of the current database:
db.runCommand({ usersInfo: 1 })You can always view your own user information. To view other users, you need the viewUser action on their database.
grantRolesToUser
db.grantRolesToUser() gives a user more roles. This lets appUser also read the reporting database:
db.grantRolesToUser("appUser", [{ role: "read", db: "reporting" }])The user's roles are now:
[
{ role: 'readWrite', db: 'products' },
{ role: 'read', db: 'reporting' }
]revokeRolesFromUser
db.revokeRolesFromUser() removes roles from a user. This removes the role you just granted:
db.revokeRolesFromUser("appUser", [{ role: "read", db: "reporting" }])The user is back to its single role, { role: 'readWrite', db: 'products' }.
dropUser
db.dropUser() deletes a user from the current database:
db.dropUser("appUser")MongoDB returns { ok: 1 }. Before you drop a user with the userAdmin or userAdminAnyDatabase role, make sure another user can still manage users.
Managing roles#
Roles grant users access to resources. MongoDB includes built-in roles, such as read, readWrite, dbAdmin, and userAdmin for a database, and clusterAdmin and root for the whole deployment. If none of them fit, you can create your own roles in a database, with exactly the privileges you need.
A privilege combines a resource, such as a database or a collection, with the actions allowed on it, such as find, insert, or update. To manage roles, you need the userAdmin or userAdminAnyDatabase role.
createRole
db.createRole() creates a role in the current database. This creates an inventoryManager role that can find, insert, and update documents in the inventory collection of the products database:
use products
db.createRole({
role: "inventoryManager",
privileges: [
{
resource: { db: "products", collection: "inventory" },
actions: ["find", "insert", "update"]
}
],
roles: []
})The roles array lists other roles that this role inherits privileges from. A role you create in a database can only include privileges on that database, except roles you create in the admin database, which can include privileges on any database or the whole cluster.
A role's name must not match a built-in role. For example, trying to create a role called clusterAdmin fails with Cannot create roles with the same name as a built-in role.
grantRolesToRole
db.grantRolesToRole() makes a role inherit the privileges of other roles. This gives inventoryManager read access to every collection in products, through the built-in read role:
db.grantRolesToRole("inventoryManager", ["read"])revokePrivilegesFromRole
db.revokePrivilegesFromRole() removes privileges from a role. The resource must exactly match the resource of the privilege in the role. This removes the update action:
db.revokePrivilegesFromRole("inventoryManager", [
{
resource: { db: "products", collection: "inventory" },
actions: ["update"]
}
])If the resource doesn't match, for example, if you name a single collection when the privilege applies to the whole database, the command succeeds but doesn't change the role.
getRole and rolesInfo
To see a role's details, use db.getRole(). Add showPrivileges: true to include its privileges:
db.getRole("inventoryManager", { showPrivileges: true })The output shows the role's own privileges, the roles it inherits, and every privilege it gets from them. After the commands above, its own privileges are:
privileges: [
{
resource: { db: 'products', collection: 'inventory' },
actions: [ 'find', 'insert' ]
}
],
roles: [ { role: 'read', db: 'products' } ],The rolesInfo command returns the same information for one or more roles, including roles in other databases, for example, db.runCommand({ rolesInfo: { role: "inventoryManager", db: "products" }, showPrivileges: true }). To list all the roles in a database, use db.getRoles().
To give the role to a user, use db.grantRolesToUser(), as shown earlier, for example, db.grantRolesToUser("appUser", ["inventoryManager"]).
dropRole
db.dropRole() deletes a role from the current database:
db.dropRole("inventoryManager")Dropping a role also removes it from every user that has it.
Embedding MongoDB documents for better performance#
Document databases like MongoDB let you design your data model around how your application uses the data, instead of fitting your application to a fixed set of tables.
A key way to do that is embedding: storing related data inside a single document. Data that your application reads together should be stored together, so it can get everything it needs in a single read. MongoDB recommends embedding by default, and using references, which store the _id of a document in another collection, when embedding doesn't fit.
Here are the most common patterns, and when to choose each one.
Embedded document pattern#
Embed related data, even complex sub-structures, in the document that uses it. For example, store a customer's addresses inside the customer document, rather than in a separate collection. Embedding reduces the number of reads, and MongoDB updates a single document atomically, so related data stays consistent.
Embedded subset pattern#
The embedded subset pattern is a hybrid. You keep a long list of related items in a separate collection, but embed a small subset of them that you show often.
For example, a movie can have thousands of reviews, stored in a reviews collection:
db.movies.findOne({ _id: 321475 })
// { _id: 321475, title: "The Dark Knight" }
db.reviews.find({ movie_id: 321475 })
// { _id: 264579, movie_id: 321475, stars: 4, text: "Amazing" }
// { _id: 375684, movie_id: 321475, stars: 5, text: "Mind-blowing" }
// ...If the movie page shows only the two most recent reviews, store those in the movie document, too:
db.movies.findOne({ _id: 321475 })
// {
// _id: 321475,
// title: "The Dark Knight",
// recent_reviews: [
// { _id: 264579, stars: 4, text: "Amazing" },
// { _id: 375684, stars: 5, text: "Mind-blowing" }
// ]
// }Now the movie page needs a single read, and the full list of reviews is still available when someone wants to see them all.
Independent access#
If your application reads or updates a piece of data on its own, give it its own collection.
For example, if a company sells a handful of products that are only shown on its profile, you can embed them in the company document. But if you also look up products directly by their stock keeping unit (SKU), or share them across companies, store them in a products collection.
Unbounded lists#
Embedding works well for short lists, but not for lists that keep growing, such as a user's activity log or the comments on a popular post. A document can't grow beyond 16 MB, and very large documents use more memory and take longer to read and update, even when you only need part of them.
If a list can grow without limit, store its items in a separate collection, with a reference to their parent.
Extended reference pattern#
The extended reference pattern is similar to the subset pattern. When a document references a document in another collection, you copy the fields you read most often from it, so you don't need a second query for them.
For example, a movie references its studio in the studios collection, and also stores the studio's name:
db.movies.findOne({ _id: 245434 })
// {
// _id: 245434,
// title: "Mission: Impossible - Ghost Protocol",
// studio_id: 924935,
// studio_name: "Paramount Pictures"
// }With studio_id, you can look up everything about the studio, and with studio_name, you can show the name without that lookup. The tradeoff is that you need to update the copied fields when the original changes, so choose fields that rarely change.
How to monitor MongoDB#
Monitoring shows you how your database uses its resources and how it performs, so you can fix problems and scale before they affect your users.
By monitoring your MongoDB databases, you can:
- Track how the database uses CPU, memory, and disk.
- Understand its current capacity, and plan when to scale.
- Detect slow queries, errors, and unusual behavior as they happen.
- Meet your service-level agreement (SLA) and data protection requirements.
If you use Atlas, its monitoring charts show the metrics below for every cluster, and the Performance Advisor suggests indexes for slow queries. On your own servers, you can collect them with the commands and tools in the next sections, or with a monitoring tool such as Prometheus or Datadog.
Key metrics to monitor#
Here are the most important MongoDB metrics, grouped by what they tell you.
Hardware metrics
- CPU usage: The share of CPU time the MongoDB process uses. Constantly high CPU often points to queries that scan too many documents, and high iowait points to a slow or overloaded disk.
- Memory: How much memory MongoDB uses. MongoDB keeps frequently used data and indexes in memory, so performance drops when they no longer fit.
- Disk IOPS and latency: How many read and write operations the disk handles, and how long they take. High latency means the disk is slowing MongoDB down.
- Free disk space: Running out of disk space stops writes, so alert on it well before it gets low.
- Swap usage: If MongoDB uses swap, the server doesn't have enough memory for the workload.
Connection and operation metrics
- Operation execution time: The average time read and write operations take. Rising times are often the first sign of a problem.
- Opcounters: The number of inserts, queries, updates, deletes, and commands per second.
- Connections: The number of open connections. A sudden spike can point to an application that doesn't reuse connections.
- Query targeting: The ratio of documents scanned to documents returned. A high ratio means queries read far more documents than they need, usually because of a missing index.
- Scan and order: The rate of queries that sort results in memory because no index supports the sort.
- Queues: The number of operations waiting to read or write. Growing queues mean the database can't keep up with the workload.
Replication metrics
- Replication lag: How many seconds a secondary is behind the primary. High lag means a secondary is struggling to keep up, and reads from it may return stale data.
- Oplog window: How many hours of operations the primary's oplog holds. If a secondary falls further behind than this, it needs a full resync.
- Replication headroom: The difference between the oplog window and the replication lag. If it approaches zero, a secondary is about to fall too far behind.
- Oplog GB per hour: How fast the primary generates oplog. An unexpected increase can point to an inefficient write workload.
MongoDB performance monitoring tools#
MongoDB includes several commands and tools that show raw performance data. You need a user with the right roles, such as clusterMonitor, to run them.
mongostat
mongostat shows a live summary of a server's activity every second, including inserts, queries, updates, deletes, memory use, queued operations, and connections:
mongostat --uri="mongodb://admin@localhost:27017/?authSource=admin"Each line shows one interval:
insert query update delete getmore command dirty used flushes vsize res qrw arw net_in net_out conn time
*0 *0 *0 *0 0 1|0 0.0% 0.0% 0 3.83G 187M 0|0 0|0 112b 174k 3 Nov 30 18:13:35.024mongotop
mongotop shows how much time MongoDB spends reading and writing each collection, which helps you find the busiest collections. The number at the end sets how often it updates, in seconds:
mongotop --uri="mongodb://admin@localhost:27017/?authSource=admin" 5mongostat and mongotop are part of the MongoDB Database Tools, which you install separately from the server, unless you use the Docker image, which includes them.
db.serverStatus()
db.serverStatus() returns a document with the server's current metrics, such as connections, operations, memory, and replication. Run it at regular intervals to track changes over time. You can also read a single section, for example:
db.serverStatus().connectionsdb.stats()
db.stats() returns storage statistics for the current database, such as the number of collections, documents, and indexes, and the size of its data and indexes.
db.collection.stats()
db.collection.stats(), for example, db.employees.stats(), returns similar statistics for a single collection, including the number of documents, the storage it uses, and its indexes. In current versions, this helper uses the $collStats aggregation stage, which replaces the deprecated collStats command.
rs.status()
rs.status() returns the status of a replica set from the point of view of the member you're connected to, including each member's state and replication progress. On a standalone server, it fails with not running with --replSet.
How to delete a MongoDB database#
To delete a database, switch to it with use, then run db.dropDatabase(). For example, to delete a database called engineers:
use engineers
db.dropDatabase(){ ok: 1, dropped: 'engineers' }Run show dbs to confirm that the database is gone. Dropping a database deletes all its collections and documents, and it can't be undone, so back it up first, for example, with mongodump, if you might need the data again.
Summary#
To get the most out of MongoDB, you need a strong understanding of the fundamentals. In this article, you learned how a MongoDB database is structured, how to create one with mongosh, Atlas, and Compass, and how to add data and manage access with users and roles. You also learned how to design documents for performance, which metrics and tools to use to monitor MongoDB, and how to delete a database.
If you're still deciding which database fits your project, see our comparison of MongoDB vs PostgreSQL.
When you're ready to deploy your app, you can run it on Sevalla's Application Hosting and connect it to MongoDB Atlas by adding your connection string as an environment variable. You can also run MongoDB itself on Sevalla from its official Docker image, with a persistent disk for its data. If a relational database suits your project, Sevalla's Database Hosting gives you managed PostgreSQL, MySQL, and MariaDB, with backups included.