Creating Collections

Lesson 4
Author : Afrixi
Last Updated : February, 2023
MongoDB - noSQL Database
This course covers the basics of working with MongoDB.

To create a collection in MongoDB, you can use the db.createCollection() method. Here’s the basic syntax:

db.createCollection(name, options)

name: The name of the collection you want to create.

options: Optional. An object containing options for the collection, such as specifying the validation rules. Here’s an example of creating a collection named “users” without any options:

> db.createCollection("users")
{ "ok" : 1 }

If the collection is created successfully, you should see a response of { "ok" : 1 }.

You can also create a collection with options. For example, to create a collection named “employees” with a validation rule that requires the “salary” field to be a number, you can use the following code:

> db.createCollection("employees", {
     validator: {
       $jsonSchema: {
         bsonType: "object",
         required: [ "name", "salary" ],
         properties: {
           name: {
             bsonType: "string",
             description: "must be a string and is required"
           },
           salary: {
             bsonType: "number",
             minimum: 0,
             description: "must be a number and is required"
           }
         }
       }
     }
   })

In this example, we’re using the $jsonSchema operator to specify the validation rules for the “employees” collection. The bsonType property specifies the type of data allowed for each field, and the required property specifies which fields are required. The minimum property in the salary field specifies that the salary must be greater than or equal to 0.

If the collection is created successfully, you should see a response of { "ok" : 1 }.