How does MongoDB create collection

In this MongoDB tutorial, We are going to learn “How does MongoDB create collection“. And we will also cover how to insert documents into a collection in MongoDB. These are the following topics that we are going to cover in this tutorial:

  • How does MongoDB create collection without data
  • How does MongoDB create collection
  • How does MongoDB create collection with index
  • How does MongoDB create collection if not exists
  • How does MongoDB create collection automatically
  • How does MongoDB insert the document into the collection
  • How does MongoDB create collection from JSON

How does MongoDB create collection without data

In MongoDB, If you want to create a collection without data or an empty collection then MongoDB provides a command that helps you to create a collection.

Syntax:

db.createCollection(collection_name)

Example:

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

Here, data is the name of the collection, This is how simply you can create a collection without data.

In this topic, you learned how to create a collection without data. This is the simplest way of creating a collection into the database without inserting any documents(data).

Read MongoDB group by count

How does MongoDB create collection

A MongoDB collection can be referred to as a group of MongoDB documents. So, for creating the collection we used this command db.createCollection(name, options).

But we don’t need to create a collection because MongoDB creates a collection automatically when we insert documents into the collection.

Syntax:

db.createCollection(name, options)

With the help of this table, you can easily understand how exactly you can use these two parameters of the createCollection() function

ParameterTypeDescription
NameStringWrite the name of the collection
that you want to create.
OptionsDocumentIn this, we write about memory size
and indexing

The options parameter is optional, there we used the following list of options:

FieldTypeDescriptions
CappedBoolean (Optional) If true, then it allows a capped collection. the capped collection is a fixed size collection that overwrites its oldest entries when it gets to its maximum size. If you declare it as true then you need to specify the size parameter also.
AutoIndexIDBoolean(Optional) If true, It automatically creates the index on the _id field.
SizeNumber (Optional) For capped collection, we have to specify the maximum size in bytes.
MaxNumber (Optional) In this, we have to specify the maximum number of documents that are allowed by capped collection.

Note that, when we insert the document into the collection, MongoDB first checks capped collection, and then it checks the max field.

Example:

Now, we are going to create a collection in MongoDB and after that insert the record(document) into the table/collection. Let’s create a collection

> use test
switched to db test
> db.createCollection("database")
{ "ok" : 1 }

Our collection is Successfully created. You can also check the collection is created or not by using the command show collections.

> show collections
database

There is one more example, In which you understand how you can use all createCollection() method

> db.createCollection("mydb", {capped : true, size : 1024, max : 1000 })
{ "ok" : 1 }

In this example, mydb is the collection name. Here, we also use some of the options like capped is used for fixed-size collection, and we have defined size and max for maximum size, the maximum document we can allow respectively.

In this topic, you learned how to create a collection and also studied all are the parameter of the createCollection() method.

Read: How to install MongoDB

How does MongoDB create collection with index

What is an index in MongoDB?

When we insert a document into the collection then MongoDB creates a unique index on the _id field. The use of the _id field is to stop the client from inserting two documents with the same value for the _id field.

Basically, we can say that indexes in MongoDB are the same as indexes in other database systems. The difference is in MongoDB we define indexes at the collection level.

There are various index types provided by MongoDB:

  • Single Field
  • Compund Index
  • Multikey Index
  • Text Index

To create an index in the Mongo shell, we use db.collection.createIndex() command.

Syntax:

db.collection_name.createIndex(keys, options)

Example:

>db.data.createIndex({Name : 1})
{
        "numIndexesBefore" : 3,
        "numIndexesAfter" : 4,
        "createdCollectionAutomatically" : false,
        "ok" : 1
}

In this example, the collection name is data and it has an index on the string field Name. Here, we can either use 1 or -1 for ascending and descending order respectively.

After executing this, it will create an index as by default name Name_1 and you can also create with a custom name as per your choice.

In this topic, you learned how to create a collection using Index and we covered this with a simple example so that you can easily understand it.

Read: MongoDB backup and restore

How does MongoDB create collection if not exists

In MongoDB for creating a collection, if not exist then you can create a collection by inserting the document(store the data) into the collection.

You can also manually create the collection by using these options:

  • Setting the Maximum size
  • Documentation validation rules

If you are unable to understand this then you can read the previous topic where I explain this in detail.

Syntax:

db.collection_name.insertOne(document)

Example:

>db.data.insertOne({"name" : "A collection is grouping of MongoDB documents"})
WriteResult({ "nInserted" : 1 })

Here you can see, data is the collection name and MongoDB creates collection when you insert the first data(document) into the collection.

Now, you can check yourself the collection is created or not by using the show collections command. This will show you all the collections that are in your database

>show collections
testing
data

In this topic, you learned how to create a collection if not exist in the database. This is the simplest way of creating a collection into the database.

Read: How to create a new database in MongoDB

How does MongoDB create collection automatically

MongoDB provides a facility like when you insert some document into the collection that is not yet created. It will automatically create the collection for you. You don’t need to create manually a collection for inserting the documents.

For creating the collection automatically, you have to check how many collections you have in

> show collections
mydb

There is only one collection we have in our database that is mydb.

Example:

Insert a document into the collection give name as guides and see it will automatically create a collection without explicitly creating.

> db.guides.insert({"name" : "MongoDB is No SQL database"})
WriteResult({ "nInserted" : 1 })

Now, again check collections and you find that it automatically creates the collection for you.

> show collections
mydb
guides

So this way it creates a collection automatically and If you want to see the inserted document in the collection then you can check it by using the find() command:

Syntax:

db.collection_name.find()

Example:

> db.guides.find()
{ "_id" : ObjectId("6111ed6ea30c00644f540b4e"), "name" : "MongoDB is No SQL database" }

Here, you can see this is the document we just inserted into the collection and it also created a unique _id for the document.

Important

In MongoDB, the collection is case-sensitive. You can understand by this example like if you have two collections guides, and Guides then always remember it always considers as two different collections in a totally valid database.

So always be remember what exactly name you are using for inserting the document.

In this topic, you learned how to create a collection automatically in the database. This way you can create a collection into the database automatically.

Read MongoDB aggregate $count with examples

How does MongoDB insert the document into the collection

In this topic, you will learn how different ways you can insert the document into the collection with examples.

There are three methods with that help we can easily insert the documents into the collection:

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

The insert() Method:

To insert the document in the MongoDB collection, we use the insert() method.

Syntax:

db.collection_name.insert(document)

Example:

>db.createCollection("testing")
> db.testing.insert({
    _id : ObjectId("507f191e810c19999de860ea"),
    title: "MongoDB Overview",
    description: "MongoDB is no sql database",
    by: "sql server guides",
    url: "https://www.sqlserverguides.com",
    tags: ['mongodb', 'database', 'NoSQL'],
    likes: 1000
 })
WriteResult({ "nInserted" : 1 }))

you can also add an array of documents by using the insert() method:

>db.createCollection("data")
>db.data.insert([
	{
		title: "MongoDB Overview",
                description: "MongoDB is no sql database",
                by: "sql server guides",
                url: "https://www.sqlserverguides.com",
                tags: ['mongodb', 'database', 'NoSQL'],
                likes: 1000
	},
	{
	title: "NoSQL Database",
	description: "NoSQL database doesn't have tables",
	by: "sql server guides",
	url: "https://www.sqlserverguides.com",
	tags: ["mongodb", "database", "NoSQL"],
	likes: 2000,
	comments: [
		{
			user:"user123",
			message: "My first comment",
			like: 10
		}
	]
}
])
BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 2,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})

Note: If you want to insert the document, you can also use db.data.save(documents) but remember these points:

  • In the document if you don’t define _id then it works same as insert().
  • If you define _id in the document then it will replace all the data as define in save() method.

The insertOne() method:

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

Syntax:

db.collection_name.insertOne(document)

Example:

>db.createCollection("userDetails")
> db.userDetails.insertOne(
	{
		First_Name: "John",
		Last_Name: "Smith",
		Date_Of_Birth: "1995-09-26",
		e_mail: "john_smith.123@gmail.com",
		phone: "1234567890"
                country: "United States of America"
	})
WriteResult({ "nInserted" : 1 })

The 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.createCollection("userDetails")
> db.userDetails.insertMany([
	{
		First_Name: "John",
		Last_Name: "Smith",
		Date_Of_Birth: "1995-09-26",
		e_mail: "john_smith.123@gmail.com",
                city: "Canada"
	},


        {
		First_Name: "Rebort",
		Last_Name: "Garcia",
		Date_Of_Birth: "1994-03-16",
		e_mail: "rebort_garcia.123@gmail.com",
                city: "Australia"
	},


        {
		First_Name: "David",
		Last_Name: "Johnson",
		Date_Of_Birth: "1991-12-10",
		e_mail: "david_johnson.123@gmail.com",
                city: "United Kingdom"
	}
])

{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("611229f01d498e98759264bd"),
                ObjectId("611229f01d498e98759264be"),
                ObjectId("611229f01d498e98759264bf")
        ]
}

In this topic, you learned how different ways you can insert documents into the database with syntax and examples.

Read: MongoDB shutting down with code 100

How does MongoDB create collection from JSON

Import data to MongoDB

In this topic, we will learn how to import the data in MongoDB. For importing the data MongoDB gives a tool that is known as mongoimport. With the help of this tool, you can easily import the files like CSV, JSON, and TSV into the MongoDB database.

This MongoDB tool mongoimport is available on the bin folder of MongoDB. If it is not available then you can download it from this link. Here, we are going to download this for windows operating systems.

You can download this tool for any operating system as per your system requirement.

How to download mongoimport tool
Download mongoimport tool

Now you need to follow these steps:

  • After downloading successfully from the above link , unzip the the downloaded folder.
  • Now goto the bin folder copy all the .EXE files and open MongoDB folder till bin folder and paste all the .EXE file here.
mongo import tool
mongo import tool
  • Now you can easily use mongoimport tool.

Import JSON file

Now, you can easily import JSON files by using the mongoimport tool.

Syntax:

mongoimport -jsonArray -db database_name -collection collection_name -file file_location

This command will help you to import the JSON file. Here you have to write mongoimport after that database name, collection name and then JSON file location(path) means a file that you want to import.

You need to follow the following steps, with that help you can easily import the file:

  • Open command prompt, start the MongoDB server
how to start mongodb server in windows
Start MongoDB server
  • Now again open command prompt and go to till bin folder of MongoDB
  • We are going to import this JSON file
import json in MongoDB
student.json file
  • Check that how many databases are right now in your MongoDB
>show dbs
admin  0.000GB
config 0.000GB
local  0.000GB
  • Open command prompt and go to till bin folder and use the below command
C:\Program Files\MongoDB\Server\5.0\bin>mongoimport --jsonArray --db info --collection student --file F:\students.json

This command successfully imports JSON file(students.json) into MongoDB. Here, in this command info is the database name and student is the collection name.

  • Open mongo shell again and check now how many database you have in MongoDB
>show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
info    0.000GB

Here you can see the JSON file is successfully imported with the database name as info.

  • If you want to check the collection name, you can check it by using
>use info
switched to db info
>show collections
student

Here, the student is the collection name that you specify in the above command.

Note: If you don’t specify the collection name then the collection name is created based on the first name of the file.

In this section, you learned how to create a collection from JSON files in the database. And we also cover this with examples and all the commands that are required to import JSON files.

Here are some of the recent tutorials.

In this tutorial, we have learned “How does MongoDB create a collection” using different approaches with examples. these are some of the topics that we covered in this article

  • How does MongoDB create collection without data
  • How does MongoDB create collection
  • How does MongoDB create collection with index
  • How does MongoDb create collection if not exists
  • How does MongoDB create collection automatically
  • How does MongoDB insert the document into the collection
  • How does MongoDB create collection from JSON