In this part of the Learn Mongo Series, we will learn how to create a collection in mongodb. We will be creating a
collection with the name details .
In mongodb database , There are 2 methods to create a collection. We can either create it using the following command
db.createCollection(name, options) or we can create it automatically by inserting the data into a document.
We will learn both the methods in detail below :
string as input.We pass collection name to be created here. boolean . It can be either true or false.
Capped collections are fixed size collections which automatically overrides its oldest entry after reaching its
maximum size. Default value is false . If capped is true , then it is mandatory
for us to give value to size param also as they are inter-dependent. Capped collections are
not recommended for sensitive data.
number .It is used to specify the maximum size for a capped collection. It specifies
size in bytes. If capped is true , then it is mandatory to give this parameter.
number . It is used to specify the maximum number of collection allowed in a capped collection.
boolean . If true, used to create an automatic index on _id field.
> use demo_db
switched to db demo_db
> db.createCollection("details")
{ "ok" : 1 }
>
> use demo_db
switched to db demo_db
> db.createCollection("details_new",{capped : true, size : 12400, max : 10000,autoIndexId : true })
{ "ok" : 1 }
>
show collections command as shown below :
> use demo_db
switched to db demo_db
> db.createCollection("details_new",{capped : true, size : 12400, max : 10000,autoIndexId : true })
{ "ok" : 1 }
>show collections
details
details_new
>
db.<collection_name>.insert({"key":"value"}) as shown below :
> use demo_db
switched to db demo_db
>db.students.insert({"name":"alex"})
{ "ok" : 1 }
>show collections
details
details_new
students
>
In this part of learn mongo series , we learned about how we can create a collection in mongodb. We learned the following commands of mongodb :
use : This command is use to either create a new database or switch to an already existing database. db.createCollection(name,options) : This command is used to create a collection manually. db.<collection_name>.insert({"key":"value"}) : This command is used to create the collection automatically by inserting
data into the document. show collections : This command is used to list all the mongodb collections of the current mongodb database on the console.