db.createCollection(name, options) is used to create collection in MongoDB. when you create a document then the collection is automatically created if it does not exist. The collection is like a table in RDBMS.
> db.createCollection("collectionName",options);
collectionName:- is a string type, specifies the name of the collection to be created.
options:- is a document type, specifies the memory size and indexing of the collection. It is an optional parameter.
Field
Type
Description
capped
Boolean
Optional. To create a capped collection you should specify true. If you specify true, you must also set a maximum size in the size field.
autoIndexId
Boolean
Optional. If you specify false then disable the automatic creation of an index on the _id field but now it is deprecated since version 3.2
size
number
Optional. Specify a maximum size in bytes for a capped collection. Once a capped collection reaches its maximum size, MongoDB removes the older documents to make space for the new documents.
max
number
(Optional) Specifies the maximum number of documents allowed in the capped collection.
> db.createCollection("employees");
Output
{ “ok” : 1 }
How to create Collection through Document?
When you create a document then it checks collection is exists or not if not exists then create automatically.
> db.collectionName.insert(objectValue);
> db.users.insert({
"name":"John",
"age":35
});
Now, check all collection in the database
> show collections
Output
employees