In the age of modern applications that demand speed and flexibility in handling vast amounts of data, NoSQL databases emerge as the ideal solution. Among them, MongoDB holds a leading position. It is a document-oriented database that allows developers to store data in dynamic, JSON-like structures instead of rigid tables.
This flexibility gives MongoDB exceptional power in building easily scalable applications. In this detailed guide, we will walk through, step-by-step, how to create a new database, manage collections, and insert data using the Node.js environment.
Before we begin, ensure you have the following:
To start interacting with the database, you must first establish a secure connection to the server. We will use the official mongodb
library for Node.js to accomplish this task. The connection process requires specifying the server's URL (URI).
In the following example, we connect to a local database running on the default port 27017
:
// Import the MongoClient
const { MongoClient } = require('mongodb');
// Define the connection URL for the local server
const url = "mongodb://localhost:27017/";
// Create a new client instance
const client = new MongoClient(url);
async function run() {
try {
// Connect to the server
await client.connect();
console.log("Successfully connected to the database!");
} finally {
// Ensure the connection is closed when finished
await client.close();
}
}
run().catch(console.dir);
This code establishes a connection to the server, prints a confirmation message upon success, and then closes the connection to ensure no processes are left hanging.
One of the most remarkable features of MongoDB is that it doesn't require you to explicitly create a database or collection beforehand. The moment you attempt to insert the first document into a collection within a non-existent database, MongoDB will automatically create them for you.
Let's connect to a database we'll call MyStoreDB
and create a collection named products
:
const { MongoClient } = require('mongodb');
const url = "mongodb://localhost:27017/";
const client = new MongoClient(url);
async function main() {
try {
await client.connect();
console.log("Connected to the server...");
// Specify the database. It will be created on the first insert operation.
const db = client.db("MyStoreDB");
// Explicitly create a collection (optional)
await db.createCollection("products");
console.log("Successfully created 'products' collection.");
} catch (err) {
console.error("An error occurred:", err);
} finally {
await client.close();
}
}
main();
In this example, we used db.createCollection()
to explicitly create the collection, which is a good practice for clearly defining the application's structure.
Data in MongoDB is stored as BSON (Binary JSON) documents, which represent the data objects in your application.
To add a single document, we use the insertOne()
method. Let's add a new product to our products
collection:
// ... (Connection code)
const db = client.db("MyStoreDB");
const product = { name: "High-Performance Laptop", price: 1200, category: "Electronics" };
const result = await db.collection("products").insertOne(product);
console.log(`A new document was inserted with the _id: ${result.insertedId}`);
// ... (Close connection)
If you need to add a batch of documents at once to improve performance, the insertMany()
method is the perfect choice.
// ... (Connection code)
const db = client.db("MyStoreDB");
const products = [
{ name: "4K Monitor", price: 300, category: "Electronics" },
{ name: "Mechanical Keyboard", price: 90, category: "Accessories" },
{ name: "Ergonomic Office Chair", price: 250, category: "Office Furniture" }
];
const result = await db.collection("products").insertMany(products);
console.log(`${result.insertedCount} documents were successfully inserted.`);
// ... (Close connection)
Every document in MongoDB must have a unique _id
field, which acts as its primary key.
_id
field when inserting a new document, MongoDB will automatically generate a unique value of type ObjectId
._id
value yourself, as long as you ensure it is unique within the collection.Here is an example of manually assigning _id
values:
// ...
const customIdProducts = [
{ _id: 1, name: 'Ballpoint Pen', stock: 150 },
{ _id: 2, name: 'Notebook', stock: 200 }
];
await db.collection("inventory").insertMany(customIdProducts);
// ...
Note: Manually assigning the _id
requires you to manage uniqueness yourself, which can be complex in large-scale applications.
After inserting data, you'll need a way to retrieve it. MongoDB provides powerful query methods. The findOne()
method is used to find the first document that matches a specific condition.
// ... (Connection code)
const db = client.db("MyStoreDB");
// Find the first document in the products collection
const firstProduct = await db.collection("products").findOne({});
console.log("Found the following document:");
console.log(firstProduct);
// ... (Close connection)
To find all documents matching a condition, you can use the find()
method, which returns a cursor that you can iterate over. To learn more about advanced queries, you can refer to the official MongoDB documentation on read operations.
In this article, we've covered the fundamentals of working with MongoDB, from connecting to the server and creating databases and collections to inserting and retrieving data. With its flexibility and power, MongoDB enables you to build modern, scalable applications with high efficiency.
Now that you've mastered the basics, you can move on to more advanced topics like Indexing to improve query speed, the Aggregation Framework for complex data analysis, and Schema Validation to ensure your data's consistency. Go ahead and start building your next project with MongoDB.