Create Collection In MongoDB

To create a collection in MongoDB, we generally don't need to create one explicitly. Collections are created automatically when we insert documents into them.

However, if we want to ensure that a collection is created or we want to create an empty collection explicitly, we can do so using the MongoDB client or a MongoDB shell.

Here's how we can create a collection in MongoDB:

Connect to MongoDB:

Before creating a Collection(table) in MongoDB, First, we need to connect to our MongoDB instance using the MongoDB shell or a MongoDB client library using our programming language.

Using the Mongo shell, we can connect to a MongoDB server running on localhost by simply typing the `mongo` command in our terminal.

Example:

mongo

Example:

show dbs;

Once our connection is established successfully, we can check databases in MongoDB using the below command:

Example:

use your_database_name;

Example:

db

Switch or Create Database:

Switch to the database where you want to create the collection using the "use" command.

To check the current database name using mongo shell.

Example:

db.createCollection("your_collection_name")

Create Collection:

Use the "createCollection()" method to explicitly create a collection.

Example:

Example:

# Create a collection named "your_collection_name" with options

db.createCollection("your_collection_name", {
   validator: { $jsonSchema: {
      bsonType: "object",
      required: [ "name", "age" ],
      properties: {
         name: {
            bsonType: "string",
            description: "must be a string and is required"
         },
         age: {
            bsonType: "int",
            description: "must be an integer and is required"
         }
      }
   }},
   validationLevel: "strict",
   validationAction: "error"
})

Example:

# Connect to MongoDB (assuming it's running locally on the default port)
mongo

# Switch to the desired database
use your_database_name

# Create a collection named your_collection_name
db.createCollection("your_collection_name")

The above command will create a collection in our specified Database.

Note: Replace "your_database_name" with the name of your database and "your_collection_name" with the name you want for your collection.

Create Collection with Schema and Validation:

We can also specify additional options when creating the collection, such as specifying the validation rules for documents in the collection or setting the size and maximum number of documents allowed in the collection.

The Above Statement will create a collection named "your_collection_name" with validation rules that require documents to have a name field of type string and an age field of type integer.

It also specifies that documents violating these rules should result in an error.

Insert Data into Collection:

Example:

Example:

db.your_collection_name.insertOne({
    name: "Alice Collin",
    age: 20
})
# Run one Query at a time

db.your_collection_name.insertOne({
    name: "Alice Collin"
})

db.your_collection_name.insertOne({
    age: 20
})

Output:

{
  acknowledged: true,
  insertedId: ObjectId('332bcb7eac36be0e09f4cf4s')
}

Checking Schema Validation:

We have created a collection named `your_collection_name` and we have added validation on `age` and `name` as required.

Checking schema validation by just passing one value at a time.

Output:

MongoServerError: Document failed validation

In Both cases, we are getting the same error while inserting incorrect document data into the collection.