{}const=>[]async()letfn</>var
DevelopmentSQL

NoSQL: Introduction to MongoDB for Beginner Developers

A complete guide to MongoDB for developers: learn the basics of NoSQL databases, learn how to work with documents and collections, master queries and data aggregation. Practical examples in JavaScript and Node.js will help you quickly start using MongoDB in your projects.

К

Kodik

Author

7 min read

What is NoSQL?

NoSQL (Not Only SQL) is an approach to database design that differs from the traditional relational model. Unlike SQL databases with their rigid table structure, NoSQL databases offer more flexible models for storing information.

The main advantages of NoSQL databases include a flexible data schema, horizontal scaling, high performance when working with large amounts of data, and the ability to work effectively with unstructured data.

🔥 100,000+ students already with us

Tired of reading theory?
Time to code!

Kodik — an app where you learn to code through practice. AI mentor, interactive lessons, real projects.

🤖 AI 24/7
🎓 Certificates
💰 Free
🚀 Start learning
Joined today

Why MongoDB?

MongoDB is a document-oriented NoSQL database. This means that data is stored as documents similar to JSON objects. This approach is especially convenient for web developers working with JavaScript, since the data structure in MongoDB naturally corresponds to objects in the code.

MongoDB has gained popularity due to several key features. First, it offers a dynamic schema, which makes it easy to change the data structure without migrations. Secondly, MongoDB provides high performance when reading and writing data. Third, the database is easily scaled horizontally through sharding. MongoDB also provides a powerful query language and supports replication to ensure fault tolerance.

Basic concepts of MongoDB

Before you start working with MongoDB, it is important to understand the basic concepts that differ from relational databases.

MongoDB uses collections instead of tables and documents instead of rows. A document is a set of key-value pairs, very similar to a JSON object. At the same time, documents in one collection can have a different structure, which ensures the flexibility of the scheme.

Each document has a unique identifier in the _id field, which is automatically generated by MongoDB if you do not specify it yourself. MongoDB uses the BSON (Binary JSON) format to store documents, which ensures efficiency and support for additional data types such as Date or Binary.

Installing MongoDB

Getting started with MongoDB is quite simple. You can install the database locally on your computer or use the MongoDB Atlas cloud service.

For local installation, visit the official MongoDB website and download the version for your operating system. On Windows, the installation is performed through the standard installer, on macOS it is convenient to use Homebrew with the brew install mongodb-community command, and on Linux the installation is performed through the package manager of your distribution.

MongoDB Atlas provides a free cloud cluster that is great for training and small projects. Just register on the MongoDB Atlas website and create your first cluster.

Getting Started with MongoDB

After installation, you can connect to MongoDB via the mongosh command shell. Let's look at the basic operations.

The database and collection are created implicitly when the data is first inserted. To switch to the database, use the use myDatabase command. MongoDB will automatically create a database when you add the first document.

To insert a document into a collection, use the insertOne or insertMany method. For example, you can add a user as follows:

db.users.insertOne({
  name: "Alexey",
  email: "alexey@example.com",
  age: 28,
  skills: ["JavaScript", "Python", "MongoDB"]
})

Search for documents is carried out by the find method. To find all users, use db.users.find(), and to find a specific user, you can apply a condition, for example, db.users.findOne({name: "Alexey"}).

Documents are updated using updateOne or updateMany. For example, you can add a skill to a user like this:

db.users.updateOne(
  {name: "Alexey"},
  {$push: {skills: "TypeScript"}}
)

Deleting documents is done through deleteOne or deleteMany. The db.users.deleteOne({name: "Alexey"}) command will delete the user's document.

Working with MongoDB in Node.js

For real applications, you will work with MongoDB through drivers or ODM (Object Document Mapper). The most popular library for Node.js is Mongoose.

Install Mongoose with the npm install mongoose command. Then connect to the database:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myapp')
  .then(() => console.log('Connected to MongoDB'))
  .catch(err => console.error('Connection error:', err));

Mongoose allows you to define schemas for your documents, even though MongoDB does not require a rigid schema:

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true,
    unique: true
  },
  age: Number,
  skills: [String],
  createdAt: {
    type: Date,
    default: Date.now
  }
});

const User = mongoose.model('User', userSchema);

Now you can create and save users through the model:

const newUser = new User({
  name: 'Maria',
  email: 'maria@example.com',
  age: 25,
  skills: ['Vue.js', 'CSS']
});

await newUser.save();

Advanced queries

MongoDB provides a rich set of operators for building complex queries.

Comparison operators allow you to search for documents by conditions. For example, you can find all users over 25 years old as follows: db.users.find({age: {$gt: 25}}). The following operators are available: $eq (equal), $ne (not equal), $gt (greater), $gte (greater than or equal), $lt (less), $lte (less than or equal), and $in (value in the array).

Logical operators help to combine conditions. The $and operator allows you to combine several conditions, $or performs a logical OR, and $not inverts the condition.

Array operators are especially useful when working with array fields. For example, $all checks for all specified elements, $elemMatch searches for array elements by a complex condition, and $size checks the size of the array.

Indexes in MongoDB

Indexes are critical to query performance. Without indexes, MongoDB scans the entire collection to find the documents you need.

You can create an index with the command db.users.createIndex({email: 1}), where 1 means ascending order, and -1 means descending order. You should create indexes for the fields you frequently search.

MongoDB supports various types of indexes: single indexes for one field, composite indexes for several fields, text indexes for full-text search, and geospatial indexes for working with coordinates.

To view existing indexes, use db.users.getIndexes(), and to delete an index, use db.users.dropIndex("index_name").

Data aggregation

The aggregation framework in MongoDB allows you to perform complex data processing, similar to GROUP BY in SQL, but much more powerful.

Aggregation works like a conveyor, where data sequentially passes through the processing stages. For example, to calculate the number of users by age:

db.users.aggregate([
  {
    $group: {
      _id: "$age",
      count: {$sum: 1}
    }
  },
  {
    $sort: {count: -1}
  }
])

The main stages of aggregation include $match for filtering documents, $group for grouping and calculations, $sort for sorting, $project for selecting and converting fields, $limit and $skip for pagination, and $lookup for combining data from different collections.

When to use MongoDB

MongoDB is not suitable for all projects. Let's consider when its use is justified.

MongoDB is great for applications with a rapidly changing data schema, content management systems and blogs, real-time applications, catalog and product systems, IoT applications with a large data stream, and analytical systems with large amounts of data.

However, MongoDB may not be the best choice for systems with multiple entity relationships, where traditional SQL databases with JOIN queries are more efficient. Also, for applications that require complex transactions with multiple operations, classic relational databases may be preferable. In systems with a rigid data structure that rarely changes, the benefits of NoSQL may not be so noticeable.

MongoDB Security

Security is critical for any database.

Always enable authentication and create users with the minimum necessary rights. Do not use the root account for applications. Configure network restrictions so that MongoDB is only accessible from trusted networks. Use SSL/TLS to encrypt connections.

Back up your data regularly. MongoDB provides mongodump and mongorestore tools for creating and restoring backups. In the production environment, use replication to ensure fault tolerance.

Conclusion

MongoDB is a powerful and flexible database that is great for modern web applications. The document-oriented data model naturally corresponds to the structure of objects in the code, and the absence of a rigid scheme allows you to quickly iterate and adapt to changing requirements.

Getting started with MongoDB is quite simple, but effective use requires an understanding of its features and differences from relational databases. Proper schema design, the use of indexes, and understanding query patterns will help you build a productive and scalable solution.

Keep exploring MongoDB's capabilities, experiment with aggregation, and master replication and sharding. This database offers far more capabilities than we could cover in the introductory article, and a deep knowledge of MongoDB will be a valuable skill in your developer's arsenal.

If you want to deepen your knowledge in programming and learn MongoDB in more detail, join the educational platform Code. Here you will find structured courses in JavaScript, Python, databases and other technologies, as well as get support in active Telegram community developers. It's easier to learn together — share your experience, ask questions and develop together with like-minded people!

🎯Stop procrastinating

Liked the article?
Time to practice!

In Kodik, you don't just read — you write code immediately. Theory + practice = real skills.

Instant practice
🧠AI explains code
🏆Certificate

No registration • No card