Skip to main content

Databases and Collections

Create Database

Creating a new database in MongoDB is a straightforward process. Below are the steps to create a new database using different methods:

Using MongoDB Shell

  1. Connect to MongoDB Server: Open your terminal and connect to the MongoDB server using the mongo command.

    mongo
  2. Create or Switch to Database: Use the use command followed by the database name to create a new database. If the database doesn't exist, MongoDB will create it for you.

    use newDatabaseName

    You'll see a message like:

    switched to db newDatabaseName
  3. Insert Data: A database without any collection and data is not listed in MongoDB. To list it, you need to insert some data into it.

    db.collectionName.insert({key: "value"})

Using MongoDB Compass

  1. Open MongoDB Compass: Launch the MongoDB Compass application and connect to your MongoDB server.

  2. Create Database: Click on the "Create Database" button as shown in below image. Create db button

  3. Enter Details: Provide the database name and the name of the initial collection, then click "Create Database". Create db button

Using a Programming Language (Node.js Example)

You can also create a new database using various programming languages. Here's how you can do it using Node.js and the MongoDB native driver:

  1. Install MongoDB Driver:

    npm install mongodb
  2. Connect and Create Database:

    const MongoClient = require('mongodb').MongoClient;
    const url = "mongodb://localhost:27017/";

    MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    const dbo = db.db("newDatabaseName");
    console.log("Database created!");
    db.close();
    });
  3. Insert Data: Similar to the shell method, you'll need to insert some data to make the database appear in listings.

    dbo.collection("collectionName").insertOne({key: "value"}, function(err, res) {
    if (err) throw err;
    console.log("Document inserted");
    db.close();
    });

Drop Database

Deleting a database in MongoDB is a straightforward but critical operation that removes all collections, documents, and indexes associated with the database. This operation is irreversible, so it should be performed with caution, especially in production environments.

How to Delete a Database

Using MongoDB Shell

  1. Connect to MongoDB: Open the MongoDB shell and connect to the MongoDB instance where the database resides.

    mongo
  2. Switch to the Database: Use the use command to switch to the database you want to delete. This is necessary even if you're not currently using the database.

    use database_name
  3. Delete the Database: Use the db.dropDatabase() command to delete the current database.

    db.dropDatabase()

    This will return an object indicating the status of the operation. A successful deletion will return { "dropped": "database_name", "ok": 1 }.

Using MongoDB Drivers

You can also delete a database programmatically using various MongoDB drivers. Here's how you can do it using Node.js:

const { MongoClient } = require('mongodb');

async function deleteDatabase() {
const client = new MongoClient('mongodb://localhost:27017/');
await client.connect();

const dbName = 'database_name';
const result = await client.db(dbName).dropDatabase();

console.log(`Database ${dbName} deleted: `, result);

await client.close();
}

deleteDatabase().catch(console.error);

Considerations

  1. Permissions: Make sure you have the necessary permissions to delete the database.

  2. Data Loss: Deleting a database is irreversible and leads to permanent data loss.

  3. Replica Sets: If you're running MongoDB in a replica set, the db.dropDatabase() command will only affect the primary node. Secondary nodes must be manually updated.

  4. System Databases: Be cautious not to delete system databases like admin, local, and config.

Create Collection

Creating a collection in MongoDB can be done in various ways, depending on the interface you're using. Here's how to create a collection using the MongoDB Shell, MongoDB Compass, and programmatically using Node.js.

Using MongoDB Shell

  1. Connect to MongoDB Server: Open your terminal and connect to the MongoDB server using the mongo command.

    mongo
  2. Switch to Database: Use the use command to switch to the database where you want to create the collection.

    use existingDatabaseName
  3. Create Collection: Use the db.createCollection() method to create a new collection.

    db.createCollection("newCollectionName")

    You'll see a message like:

    { "ok" : 1 }

Using MongoDB Compass

  1. Open MongoDB Compass: Launch the MongoDB Compass application and connect to your MongoDB server.

  2. Select Database: Navigate to the database where you want to create the new collection.

  3. Create Collection: Click on the "Create Collection" button, usually located at the top-right or bottom-left corner. Create collection

  4. Enter Details: Provide the collection name and any other optional settings, then click "Create Collection". Create collection

Using Node.js

  1. Install MongoDB Driver: If you haven't already, install the MongoDB native driver for Node.js.

    npm install mongodb
  2. Connect to MongoDB and Create Collection:

    const MongoClient = require('mongodb').MongoClient;
    const url = "mongodb://localhost:27017/";

    MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    const dbo = db.db("existingDatabaseName");
    dbo.createCollection("newCollectionName", function(err, res) {
    if (err) throw err;
    console.log("Collection created!");
    db.close();
    });
    });

Optional Settings

When creating a collection, you can also specify optional settings like capped collections, auto-indexing of the _id field, etc. For example, in the MongoDB shell:

db.createCollection("newCollectionName", { capped: true, size: 6142800, max: 10000 })

This creates a capped collection with a maximum size of 6142800 bytes and a maximum of 10000 documents.

Data format

In MongoDB, data is stored in a format called BSON (Binary JSON), which is a binary representation of JSON-like documents. The structure of how data is stored and organized in MongoDB is quite different from traditional relational databases. Here's a breakdown:

Hierarchical Structure:

  1. Database: The top-level container that holds a set of collections. A single MongoDB server can host multiple databases.

  2. Collection: Equivalent to a table in relational databases, but without a fixed schema. A collection holds one or more documents.

  3. Document: A record in a MongoDB collection is a document, which is a data structure composed of field and value pairs. Documents within a collection can have different fields.

Document Structure:

A document in MongoDB is a BSON object that looks similar to JSON. A simple example:

{
"_id": ObjectId("5f50c31b1c4ae0a63c8b9a0d"),
"name": "John Doe",
"age": 30,
"email": "john.doe@example.com",
"address": {
"street": "123 Main St",
"city": "Anytown",
"zip": "12345"
},
"hobbies": ["reading", "swimming"]
}
  • _id Field: MongoDB automatically creates an _id field if you don't provide one. This field serves as the primary key for the document.

  • Data Types: MongoDB supports various data types like strings, numbers, arrays, objects, and special types like ObjectID, Date, etc.

  • Nested Documents: As shown in the example, MongoDB supports nested documents, allowing you to store complex data structures easily.

Collections:

Collections are schema-less, meaning the documents within a collection can have different fields. However, it's generally a good practice to have a consistent structure for documents in the same collection for easier data management and querying.

Indexing:

By default, MongoDB creates an index on the _id field. You can create additional indexes on any field to improve query performance.

Storage Engines:

MongoDB supports multiple storage engines, such as:

  • WiredTiger: The default storage engine as of MongoDB 3.2, it supports compression and is optimized for high-throughput operations.

  • MMAPv1: The original storage engine for MongoDB, now deprecated.

  • In-Memory: Used for databases that require high-speed access to data but do not require data persistence.

Drop Collection

Deleting a collection in MongoDB removes the collection itself, along with all the documents, indexes, and metadata associated with it. This operation is irreversible, so it should be executed with caution, especially in production environments.

How to Delete a Collection

Using MongoDB Shell

  1. Connect to MongoDB: Open the MongoDB shell and connect to the MongoDB instance where the database and collection reside.

    mongo
  2. Switch to the Database: Use the use command to switch to the database containing the collection you want to delete.

    use database_name
  3. Delete the Collection: Use the db.collection.drop() command to delete the collection.

    db.collection_name.drop()

    This will return a boolean value. true indicates that the collection was successfully dropped, and false indicates that the collection did not exist.

Using MongoDB Drivers

You can also delete a collection programmatically using various MongoDB drivers. Here's how you can do it using Node.js:

const { MongoClient } = require('mongodb');

async function deleteCollection() {
const client = new MongoClient('mongodb://localhost:27017/');
await client.connect();

const dbName = 'database_name';
const collectionName = 'collection_name';

const result = await client.db(dbName).collection(collectionName).drop();

console.log(`Collection ${collectionName} deleted: `, result);

await client.close();
}

deleteCollection().catch(console.error);

Considerations

  1. Permissions: Ensure you have the necessary permissions to delete the collection.

  2. Data Loss: Deleting a collection is irreversible and results in permanent data loss.

  3. Indexes: Deleting a collection also removes all indexes associated with it.

  4. Replica Sets: If you're running MongoDB in a replica set, the db.collection.drop() command will only affect the primary node. Secondary nodes must be manually updated.

  5. System Collections: Be cautious not to delete system collections like system.indexes.