mongodb_create_collection

MongoDB create collection | complete tutorial in 2022

MongoDB, the industry leader in No SQL databases, can handle a very high volume of data. In this blog, I’ll explain MongoDB create collection steps. We will also go through various other methods to create a collection in mongodb. So let’s get started.

Create collection in MongoDB

mongodb_create_collection

MongoDB stores data in JSON documents in mongo collections. MongoDB collections are similar to RDBS tables.

Before creating a collection, create the database first. Type the below command to create a database name naiveskill

Mongodb create database

use naiveskill
mongodb create database

type the below command to verify the current database in which the user is:

> db
naiveskill

Now it’s time to create the collection. Use mongodb createCollection command to create a collection in mongodb. The createCollection command follows the below syntax:

db.createCollection(name, options)

Where

  • Name: Name of the collection to be created in string format
  • Options : (optional)options about memory size and indexing.

Now Type the below command a create a basic collection name test

db.createCollection('test')
mongodb_create_collection

Verify the test collection by typing the below command

show collections
test

Fantastic, Now you know how to create a basic collection in MongoDB. Next, I will be explaining to you how to create a collection in mongodb with schema.

Mongodb create collection with schema

Mongodb create collection with schema

There are numerous ways to create a collection with schema in mongodb. Still, the simplest one is by using JSON schema validator.Json schema validated, validates the data schema before inserting the record. If the document you are inserting does not adhere to the schema defined, that record will be discarded.

Let’s proceed further and create a collection name Inventory with three fields ‘brand’, ‘year’, and ‘model’.

Mongodb create collection with schema and document validation

db.createCollection('Inventory', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: ['brand', 'year', 'model'],
      properties: {
        title: {
          bsonType: 'string',
          description: 'must be a string and is required'
        },
        brand: {
          bsonType: 'string',
          description: 'must be a string and is required'
        },
        Year: {
          bsonType: 'string',
          description: 'must be an string and is required'
        },
        model: {
          bsonType: 'string',
          description: 'must be an array and is required',
              }
            }
         }
      }
});

If you are getting Ok in the result, it means your collection will be successfully created.

mongodb create collection with schema

Insert Document with invalid schema in mongodb collection

Let’s insert the document into the Inventory collection by typing the below command.

db.Inventory.insertOne({brand:"iphone",model:"6s"})
Insert Document with invalid schema in mongodb collection

The document has not been inserted into the inventory collection because the Inventory collection expects three fields, and we have just passed two fields.

Insert Document with valid schemain mongodb collection

Now let’s insert a document into the mongodb collection by specifying all the mandatory fields.

> db.Inventory.insertOne({brand:"iphone",year:"2015",model:"6s"})
{
	"acknowledged" : true,
	"insertedId" : ObjectId("6129f22afe4e5ef36181631a")
}
>

As you can see from the above output, that data gets correctly inserted into the mongodb collection without any error.

Create collection in mongodb compass

In this session, we will learn how to insert data into a mongodb collection using a mongodb compass.

You can follow this link to download the Mongodb compass.

Open the Mongodb compass and paste the below connection string to connect to mongodb.

mongodb://localhost:27017/admin
mongodb compass connection

Click on create a database to create a new database.

mongodb compass create database

Now provide the database name and a collection name

mongodb compass create database

Click on create a database to create the naive database and testnaive collection.

Note: While creating a mongodb collection, you have the option to select a capped collection or custom collection, or time-series collection. More details about such types of collections can be found here.

Now, Click on database naive, and it will show you all the collections under it.

mongodb compass create collection

Similarly, the new collection can be created by clicking on CREATE COLLECTION button.

MongoDB create collection if not exist

Sometimes we need to check if the collection already exists before creating a new one. You can use the below command to check if the collection already exists in mongodb before creating a new one.

db.getCollectionNames({name: "collection_name>"}, 
	function(err, names) {console.log('Exists: ', names.length < 0)
	});

But this method is not recommended. The simplest way will be to use any programming language like python or node js to interact with MongoDB. You can follow this link to have a basic idea about how to interact with mongodb using python.

In the python client, you can type the below command to get a list of collections.

import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
client['database_name>'].list_collection_names()

Explanation

  • First, we import the pymongo client in the python shell. Please make sure you to downloaded the pymongo package before importing.
  • Then in the second step, we are creating a mongo client.
  • Then finally using the mongo client we are listing all collections in a particular database.

Mongodb create collection nodejs

Mongodb has many drivers using which you can interact with Mongodb, and one such driver is node.js. The MongoDB Node.js driver allows Node.js applications to connect to MongoDB and work with data.

Save the below command into a file name create_test_collection.js to create a database name naiveskill in the test database.

// import mongodb 
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/test";
//client connect 
MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  dbo.createCollection("naiveskill", function(err, res) {
    if (err) throw err;
    console.log("Collection created!");
    db.close();
  });
});

Now run the below command using node.

node create_test_collection.js
Collection is created!

Awesome, You have successfully created a collection using node.js.

Mongodb create collection python

Python is the first choice of data scientists and data engineers for language selection. This is because of the vast community support and multiple available packages.

And MongoDB, one of the most famous No SQL databases, can be used to build web applications, JSON APIs, etc.

To connect MongoDB with python, we can use the pymongo driver. It is the official driver provided by MongoDB.

Before creating a collection in mongodb, a database must be created. To create a database, a mongo client needs to be created. Once the client gets created

import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client['naiveskill']

Now type the below command to create a collection name mycollection

collection = db['myCollection']

Delete a mongodb collection

Deleting a collection in mongodb is quite simple. We can use the drop() command to delete a collection in mongodb.

Type the below command to delete the Inventory collection that we created earlier

db.Inventory.drop()
true

Mongodb create document

Mongodb creating documents means inserting a document in the mongodb collection. In mongodb, you have the flexibility to insert either a single document or multiple documents at once.

Mongodb insert single documents

With the mongodb insert command, we can insert a single document into the mongodb collection.

Type the below command to insert a document in the tech collection

db.tech.insert(
 {
 'Kind': 'Mobile',
 'lang': 'iphone 6s',
 'Rating': 4.2
})
> db.tech.insert(
...  {
...  'Kind': 'Mobile',
...  'brand': 'iphone 6s',
...  'Rating': 4.2
... })
WriteResult({ "nInserted" : 1 })

Mongodb insert multiple documents

Similarly, using mongodb to insert many commands, we can insert multiple documents into the mongodb collections.

> db.tech.insertMany([
... {
...     'Kind': 'Mobile',
...     'lang': 'iphone 6s',
...     'Rating': 4.2
...  },
... {
...     'Kind': 'laptop',
...     'lang': 'acer',
...     'Rating': 3.9
...  },
...  {
...     'Kind': 'mobile',
...     'lang': 'samsung',
...     'Rating': 4.0
...  },
...  ])
{
  "acknowledged" : true,
  "insertedIds" : [
    ObjectId("60c37883a9c3d411ad96c6e7"),
    ObjectId("60c37883a9c3d411ad96c6e8"),
    ObjectId("60c37883a9c3d411ad96c6e9")
  ]
}

You can follow this link to get the complete tutorial on mongodb commands.

Conclusion

Finally, we have come to the end of this basic mongodb create collection tutorial. In this tutorial, we have learned different ways to create a collection in mongodb.

I hope you have liked this tutorial. Please do let me know in the comment box if you face any issues while following along.

More to read

How to create a database in mongodb

Install MongoDB using docker

MongoDB vs Mysql

Mongodb vs PostgreSQL

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top