Introduction
In this lab, you will learn essential techniques for handling common errors in MongoDB. Using the MongoDB Shell (mongosh), you will practice identifying and resolving various issues, including connection failures, duplicate key errors, and data validation errors. By the end of this lab, you will have a practical understanding of how to make your database operations more reliable and robust.
Connecting to MongoDB and Handling Errors
Connection errors are a common issue when working with any database. They can occur for several reasons, such as an incorrect server address, network problems, or the database server not running. In this step, you will learn how to identify a connection error and then connect successfully.
First, attempt to connect to a MongoDB instance on a port where it is not running. The default port for MongoDB is 27017. We will try connecting to port 27018.
Execute the following command in your terminal:
mongosh "mongodb://localhost:27018"
This command fails and returns an error because the shell cannot find a MongoDB server at the specified address. The output will look similar to this:
MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27018
The MongoNetworkError clearly indicates a failure to connect. The ECONNREFUSED part tells you that the target machine actively refused the connection, which usually means no service is listening on that port.
Now, let's connect to the correct port. The MongoDB service was started for you during the setup phase. To connect to it, run the mongosh command without any arguments. This will use the default connection string mongodb://127.0.0.1:27017.
mongosh
Upon successful connection, you will see a welcome message and the test> prompt, indicating you are connected to the default test database.
Current Mongosh Log ID: ...
Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.2.6
Using MongoDB: 8.0.0
Using Mongosh: 2.2.6
...
test>
You are now connected to the MongoDB server. Please keep this terminal open and remain in the mongosh shell for the following steps.
Handle Duplicate Key Errors
Maintaining data integrity is crucial for any application. One of the most common data integrity issues is duplicate records. MongoDB prevents this through unique indexes, which ensure that an indexed field does not store duplicate values.
You should already be in the mongosh shell from the previous step. First, switch to a new database named errorlab. A database is created automatically when you first store data in it.
use errorlab
Next, create a unique index on the email field in a new users collection. This command tells MongoDB that every document in the users collection must have a unique value for the email field.
db.users.createIndex({ email: 1 }, { unique: true });
The output confirms the index was created successfully.
{
"numIndexesBefore": 1,
"numIndexesAfter": 2,
"createdCollectionAutomatically": true,
"ok": 1
}
Now, insert a document into the users collection. This operation will succeed because the collection is empty and the email is unique.
db.users.insertOne({ name: "John Doe", email: "john@example.com" });
You will see a confirmation message with the ID of the inserted document:
{
"acknowledged": true,
"insertedId": ObjectId("...")
}
Next, attempt to insert another document with the exact same email address.
db.users.insertOne({ name: "Jane Doe", email: "john@example.com" });
This time, the operation fails. MongoDB returns a MongoBulkWriteError with a specific error code, E11000, which signifies a duplicate key error. This is the expected behavior to protect data integrity.
MongoServerError: E11000 duplicate key error collection: errorlab.users index: email_1 dup key: { email: "john@example.com" }
Resolve Duplicate Keys with Upsert
Preventing duplicates is good, but sometimes you want to update a record if it exists or create it if it does not. This "update or insert" logic is a common requirement. MongoDB provides a clean way to do this using the upsert option.
Let's try to update the user with the email john@example.com. We will use the updateOne method with the upsert option set to true.
db.users.updateOne(
{ email: "john@example.com" },
{ $set: { name: "John Doe Updated", lastUpdated: new Date() } },
{ upsert: true }
);
The output shows that one document was matched and modified. The upsertedId is null because an existing document was updated, not a new one inserted.
{
"acknowledged": true,
"matchedCount": 1,
"modifiedCount": 1,
"upsertedId": null
}
Now, let's run a similar command for a user who does not exist yet, jane@example.com.
db.users.updateOne(
{ email: "jane@example.com" },
{ $set: { name: "Jane Doe", lastUpdated: new Date() } },
{ upsert: true }
);
This time, the output shows that matchedCount is 0, but a new document was created, as indicated by the upsertedId.
{
"acknowledged": true,
"matchedCount": 0,
"modifiedCount": 0,
"upsertedId": ObjectId("...")
}
To verify the results, you can query the collection to see all documents. The pretty() method formats the output for easier reading.
db.users.find().pretty();
The output will display both documents: John's document with the updated name, and Jane's newly created document. The upsert option provides a powerful and atomic way to handle "create or update" scenarios.
Handle Query and Validation Errors
Errors can also occur when you query data or when inserted data does not conform to predefined rules. In this step, you will explore a query syntax error and a data validation error.
First, let's see what happens when you use a query operator that does not exist. This is a common typo.
db.users.find({ name: { $invalidOperator: "John" } });
MongoDB immediately returns an error because it does not recognize $invalidOperator.
MongoServerError[BadValue]: unknown operator: $invalidOperator
Next, let's explore a more powerful feature: schema validation. You can define rules that documents must follow to be inserted or updated in a collection. Let's create a new products collection with a validator that requires a name (string) and a price (number).
db.createCollection("products", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "price"],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
price: {
bsonType: "number",
description: "must be a number and is required"
}
}
}
}
});
Now, attempt to insert a document that violates this schema by providing the price as a string instead of a number.
db.products.insertOne({ name: "Laptop", price: "1200" });
The operation fails with a MongoBulkWriteError. The message Document failed validation clearly states the reason, preventing bad data from entering your database.
MongoServerError: Document failed validation
...
Finally, insert a valid document that conforms to the schema.
db.products.insertOne({ name: "Laptop", price: 1200 });
This operation succeeds because the document is valid.
{
"acknowledged": true,
"insertedId": ObjectId("...")
}
Schema validation is a powerful tool for enforcing data consistency directly within the database.
Summary
In this lab, you have learned how to handle several common types of MongoDB errors using the mongosh shell. You started by identifying and resolving a connection error. Then, you enforced data integrity by creating a unique index to prevent duplicate key errors. You also learned how to use the upsert option to gracefully handle "update or insert" logic. Finally, you explored query syntax errors and used schema validation to prevent invalid data from being saved to your database. These fundamental error-handling skills are essential for building reliable and robust applications with MongoDB.

