Learning MongoDB

0% completed

Previous
Next
MongoDB – Database, Collection, and Document

In this lesson, we will explore the below components of MongoDB:

  • Database
  • Collection
  • Document

Understanding these fundamental concepts is crucial for effectively working with MongoDB. We will cover what each component is, how they are structured, and how to create and manage them using MongoDB commands.

MongoDB Database

A database in MongoDB is a container for collections. Each database contains its own set of collections, and each collection contains its own set of documents. Databases are completely independent from each other. Each database has its own permissions, users, and configuration settings.

Naming Rules for Databases

When naming databases in MongoDB, you should follow these rules:

  • Database names can be any UTF-8 string.
  • They cannot be empty.
  • They must not contain the characters \, /, $, . ", *, <, >, :, |, ?, or null characters.
  • The name must be fewer than 64 characters in length.

Creating a Database

Creating a database in MongoDB is straightforward. You can create a database by using the use command, which switches the context to the specified database. If the database does not exist, MongoDB will create it when you insert data into it.

Example:

use myDatabase

This command switches to myDatabase. If myDatabase does not exist, it will be created when you add the first collection or document.

Managing Databases

To view all databases on your MongoDB server, use the show dbs command:

show dbs

To drop a database, use the db.dropDatabase() command:

db.dropDatabase()

This command drops the current database. Make sure to switch to the database you want to drop before executing this command.

MongoDB Collection

A collection in MongoDB is a grouping of MongoDB documents. Collections are equivalent to tables in relational databases. Collections do not enforce any schema, allowing documents within a collection to have different fields and data types.

Naming Rules for Collections

When naming collections in MongoDB, you should follow these rules:

  • Collection names can be any UTF-8 string.
  • They cannot be empty.
  • They must not contain the null character (0x00).
  • Collection names should not begin with the system prefix (system.), which is reserved for internal collections.
  • The name must be fewer than 120 bytes in length.

Creating a Collection

Collections are typically created implicitly when you insert a document into them. However, you can also create a collection explicitly using the createCollection method.

Example:

db.createCollection("myCollection")

This command creates a collection named myCollection in the current database.

Managing Collections

To view all collections in the current database, use the show collections command:

show collections

To drop a collection, use the db.collection.drop() command:

db.myCollection.drop()

This command drops the myCollection from the current database.

MongoDB Document

A document in MongoDB is a record in a collection. Documents are stored in a JSON-like format called BSON (Binary JSON). Each document contains a set of key-value pairs, where the keys are strings and the values can be various data types, including strings, numbers, arrays, and nested documents.

Naming Rules for Documents

While MongoDB does not impose specific naming rules for documents (since they are essentially key-value pairs within collections), there are best practices to follow:

  • Use meaningful field names.
  • Avoid using reserved characters and words.
  • Be consistent in naming conventions to ensure maintainability.

Key Points

  • Documents can have different structures within the same collection.
  • Each document must have a unique _id field, which acts as the primary key.

Creating a Document

To create a document, use the insertOne or insertMany method. Here is an example of inserting a single document into a collection:

db.myCollection.insertOne({ name: "John Doe", age: 30, email: "john.doe@example.com" })

This command inserts a document with the fields name, age, and email into the myCollection collection.

Examples

  1. Inserting Multiple Documents:

    db.myCollection.insertMany([ { name: "Alice", age: 25, email: "alice@example.com" }, { name: "Bob", age: 28, email: "bob@example.com" } ])

    This command inserts two documents into the myCollection collection.

  2. Finding Documents:

    db.myCollection.find()

    This command retrieves all documents in the myCollection collection.

  3. Finding Documents with a Condition:

    db.myCollection.find({ age: { $gt: 25 } })

    This command retrieves all documents where the age field is greater than 25.

  4. Updating a Document:

    db.myCollection.updateOne( { name: "John Doe" }, { $set: { age: 31 } } )

    This command updates the age field of the document where the name field is "John Doe".

  5. Deleting a Document:

    db.myCollection.deleteOne({ name: "John Doe" })

    This command deletes the document where the name field is "John Doe".

Notes

  • Atomic Operations: Operations within a single document are atomic. This means that updates to a document will either fully complete or fully fail, ensuring data integrity within that document.
  • Nested Documents: MongoDB supports embedded documents, allowing you to nest documents within other documents. This provides a powerful way to model complex data relationships within a single document.

Understanding the core components of MongoDB – Database, Collection, and Document – is essential for working effectively with MongoDB. Databases act as containers for collections, collections group related documents, and documents are the individual records containing data. By mastering these concepts and the associated commands, you can efficiently create, manage, and manipulate data in MongoDB.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next