Create tables in MongoDB (Complete Guide)

In this MongoDB tutorial, We will learn “How to create tables in MongoDB“. And we will also perform different operations while creating the tables in collections.

These are the following topics that we are going to cover in this tutorial:

  • How to create table in MongoDB
  • How to create table in MongoDB using primary key
  • How to create table in MongoDB using foreign key
  • How to create table in MongoDB compass
  • How to create table in MongoDB using python
  • How to create table in MongoDB using Ubuntu

How to create table in MongoDB

In MongoDB, For creating the table first of all you have to create a collection. The collection works the same as we create a table while inserting the data into a relational database.

Syntax:

> db.createCollection("collection_name")

Example:

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

In this example, we created the Student collection. You can also check that it is created or not by using the “show collections” command.

> show collections
EmpInfo
Student

Here you can see the Student collection created successfully into the database.

There are three methods that you can use for inserting the documents(data) into the table(collection):

  • insert()
  • insertOne()
  • insertMany()

The insert() Method:

To insert the document in the MongoDB collection, you have to use the insert() method.

Syntax:

db.collection_name.insert(document)

Example:

> db.students.insert({
            "fname":"Ron", 
            "city":"Dubai", 
            "courses":[
                         "python", 
                         "django", 
                         "node"
                      ]
})
WriteResult({ "nInserted" : 1 })

Note: There is one more way by using that you can insert the data into table db.data.save(documents) but remember these points:

  • While inserting the data in the collection(table), If you don’t define _id field then it works same as the insert() method.
  • If you define _id field in the document then it will replace previous one with the data define in the save() method.

The insertOne() method:

The insertOne() method is used when you want to insert only one document into the collection.

Syntax:

db.collection_name.insertOne(document)

Example:

db.product.insertOne({
        "_id" : 6,
        "item" : {
                "name" : "BMW X7",
                "item" : "BMW"
        },
        "price" : 60.9
})
{ "acknowledged" : true, "insertedId" : 6 }

Here, the product is the collection(table) name and we inserted only one document by using the insertOne() method.

insertMany() method:

The insertMany() method is used for inserting multiple records, by using this you can pass an array of documents.

Syntax:

db.collection_name.insertMany(document)

Example:

>db.product.insertMany([
        {
        "_id" : 7,
        "item" : {
                "name" : "Audi A1",
                "item" : "Audi"
        },
        "price" : 70.16
        },

        {
        "_id" : 8,
        "item" : {
                "name" : "Bugatti Veyron",
                "item" : "Bugatti"
        },
        "price" : 90.21
        }
])
{ "acknowledged" : true, "insertedIds" : [ 7, 8 ] }

In the example using InsertMany() method, we inserted two documents in the product collection(table).

Note that while using the insertMany() method don’t forget to use a square bracket and separate multiple documents in the square bracket using a comma.

Read: How to install MongoDB

How to create table in MongoDB using primary key

What is a primary key?

The primary key is a unique identifier for each record. With the help of a unique identifier, you can easily access the data. It is also called a primary keyword.

In MongoDB, _id Field is reserved for the primary key and that should be always unique. If you don’t define the _id field in the collection(table) then it will automatically create by the MongoDB Id object and you can also put any unique information into this field.

Example:

> db.books.insertMany([
        {title: "MongoDB is NoSQL database"},
        {title: "Binary JSON format"},
        {title: "MongoDB open-source database"}
])
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("611b5a30a60b5002406571c4"),
                ObjectId("611b5a30a60b5002406571c5"),
                ObjectId("611b5a30a60b5002406571c6")
        ]
}

In this example, we inserted data into the books collection and it assigned automatically a unique ID to each document. You can also check it by using the find() method.

>db.books.find().pretty()
{
        "_id" : ObjectId("611b5a30a60b5002406571c4"),
        "title" : "MongoDB is NoSQL database"
}
{
        "_id" : ObjectId("611b5a30a60b5002406571c5"),
        "title" : "Binary JSON format"
}
{
        "_id" : ObjectId("611b5a30a60b5002406571c6"),
        "title" : "MongoDB open-source database"
}

Here, you can see a unique Id is allotted to each document.

Read: How to create new database in MongoDB

How to create a table in MongoDB using foreign key

What is a foreign key?

It is a column or a group of columns that works with two tables as a cross-reference. In the parent table, there is a primary key column that is used by another column from the child table.

In MongoDB, There is no concept of foreign keys. The foreign key only works with relational databases. For storing the data into MongoDB we use collections, objects, and fields instead of using tables, columns, and rows.

There are two ways for storing the data into MongoDB:

  • Normalization: For storing diffrent data into diffrent collection, we use normlization.
  • Denormalization: For storing diffrent data into same collection, for this we use denormalization.

Read: MongoDB backup and restore

How to create table using MongoDB compass

For creating the collection(table), you need to follow these steps:

  • Open MongoDB Compqss
  • Click on create database button.
How to create table in MongoDB compass
create a table in MongoDB compass
  • This will open a new tab, enter database and collection name and click on create database button.
create a  new database in MongoDB compass
creating a new database in MongoDB compass
  • Now we created database company and collection(table) EmpInfo.
create table in MongoDB compass
create a database in MongoDB compass

You can also insert the data into a collection(table). For inserting the data you have to import the file either JSON or CSV and store the data into a collection.

Import JSON file into MongoDB compass
Import JSON file into MongoDB compass

Now you can access the data and perform different operations into data.

create new table in MongoDB compass
datasets after importing JSON file

Read: How does MongoDB create collection

How to create a table in MongoDB using python

For creating the collection(table) in MongoDB using python, use the database object and define the name of the collection(table) you want to create.

Example:

Create a collection called as customers

import pymongo

myclient = pymongo.MongoClient("mongodb://127.0.0.1:27017/")
mydb = myclient["mydatabase"]

mycol = mydb["customers"]

Here, pymongo is a library for using MongoDB in python, and for making connections b/w MongoDB and python we use the MongoClient class. And mydatabase and customers are the database and collection respectively.

Note that MongoDB a collection only shows when we insert some content.

mydict = { "name": "Honey", "address": "Highway 786" }

x = mycol.insert_one(mydict)

Here we insert data into collection(table) by using insertOne() method.

> show dbs
admin       0.000GB
config      0.000GB
local       0.000GB
mydatabase  0.000GB

> use mydatabase
switched to db mydatabase

> show collections
customers

Now, you can check the database and collection(table) is successfully created.

Read: Pros and cons of MongoDB

How to create a table in MongoDB using Ubuntu

In Ubuntu, creating the table in the MongoDB database is easy. It is pretty similar as we create a collection(table) in the windows operating system.

You need to follow the following steps:

  • Start the MongoDB server
$ sudo service mongod start
  • Check server is running or not
$ sudo service mongod status
  • Run the MongoDB
$ mongo

Now MongoDB started and you can create a database and collection(table).

> show dbs
admin       0.000GB
config      0.000GB
local       0.000GB
  • show dbs, print all the database that are in your database.
>use Company;
switched to db Company
  • use Company, create the new database in MongoDB.
>db.createCollection("EmpInfo")
{ "ok" : 1 }
  • Using createCollection(), we created the EmpInfo collection(table).
>show dbs
Company     0.000GB
admin       0.000GB
config      0.000GB
local       0.000GB
  • Here, you can see Company collection(table) is created successfully.

You may also like reading the following articles.

In this article, you learned how to create tables in MongoDB with different operations and examples. These are the following topics that we covered in this article

  • How to create table in MongoDB
  • How to create table in MongoDB using primary key
  • How to create table in MongoDB using foreign key
  • How to create table in MongoDB compass
  • How to create table in MongoDB using python
  • How to create table in MongoDB using Ubuntu

Leave a Comment