MongoDB - Create a Collection
You can create a collection using the
createCollection() method, or on the fly as you insert a document.
Collections are like containers for related documents. They are typically used to group documents of a similar topic. For example, you could have collection names such as users,
When we created our database, we created a collection called artists. This collection will contain documents with artist details, such as the artists' names, albums they've released, etc.
Two ways to Create a Collection
Here are two ways of creating collections:
- You can create a collection on the fly when inserting a document (using the
- You can also create a collection explicitly, using the
On the Fly
When you use the
insert() method to insert a document, you specify the collection that the document will be inserted into. If the collection doesn't already exist, it will be created.
This is the method that we used previously when we created our
artists collection while inserting a document.
Here's the code that we used:
In this case, the
artists collection didn't previously exist so it was created for us.
You can also create collections using the
createCollection() method. This allows you to create a collection without inserting a document.
Here's an example of using the
You can also specify options for the collection by using the
db.createCollection(name, options) syntax.
Here's an example:
The fields available as of MongoDB version 3.2 are as follows.
||boolean||When set to
||number||Maximum size in bytes for a capped collection. Only used with capped collections (it is ignored in other collections).|
||number||Maximum number of documents allowed in the capped collection. Note that the
||boolean||Only available in the MMAPv1 storage engine. This field has been deprecated since version 3.0.|
||boolean||Only available in the MMAPv1 storage engine. Disables the power of 2 sizes allocation for the collection. Defaults to
||document||Only available in the WiredTiger storage engine. Allows configuration to the storage engine on a per-collection basis when creating a collection. Syntax is as follows:
||document||Allows you to specify validation rules or expressions for the collection. Note that validation is only applied when inserting and updating data. Therefore, data that already exists in the database is not validated (until it is updated).|
||string||Allows you to specify how strictly any validation rules are applied to existing documents during an update. Possible values:
||string||Specifies whether an error should occur, or just a warning, when invalid documents are inserted. If an error, the invalid documents will still be inserted, but with a warning.
||document||Allows you to specify a default configuration for indexes when creating a collection. Accepts a