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.
> db.createCollection("employees");
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
Create Collection – Interview Questions
Q 1: What is a collection in MongoDB?
Ans: A collection is a group of MongoDB documents.
Q 2: How do you create a collection?
Ans: Use db.createCollection("collectionName").
Q 3: Can MongoDB create collections automatically?
Ans: Yes, collections are automatically created when inserting documents.
Q 4: How do you view collections?
Ans: Use show collections.
Q 5: Can you define options while creating collections?
Ans: Yes, options like validation rules and capped collections can be defined.