MongoDB - Collection Operations
Databases can contain collections. Collections can contain one more more document. Closest example from the relational world for collections is tables.
Setting Up
To create a collection, we need to first specify the database that we will be using. Let's switch to the database test:
Creating Collections
Now – to create a collection the command db.createCollection can be used.
To create a simple collection for users:
Note
Note that we do not specify any kind of data type / schema information. Any kind of data can be stored inside collections.
Capped Collections
When creating MongoDB collections, we can also specify some additional options for the collection. One useful option is to utilize capped collections.
Capped collection allows you to pre-set how much space can the collection take and additionally how many documents can be inserted in the specified collection.
When new documents are added in the collection and the collection takes more space than allocated, it automatically starts removing old documents.
To create a capped collection with a size of 10000000 bytes (7 zeros = 10 Mb) and a maximum amount of 5000 documents, use this command:
Removing Collections
To remove (drop) a collection, the command db.collection.drop() can be used.
Example below:
Listing Collections
To list the collections in the currently selected (used) database, the command db.getCollectionNames() or show collections can be used:
The difference between these two commands is that the first one returns the data back in array that can be further used for example with the Javascript Shell.
And to list more specific information about the collections (like if it is capped), the command db.getCollectionInfos() can be used:
Example Output
[
{
name: 'logEvents',
type: 'collection',
options: { capped: true, size: 100000000, max: 5000 },
info: {
readOnly: false,
uuid: UUID("2b2b08a9-4c2a-4c15-b219-1209455f8d91")
},
idIndex: { v: 2, key: { _id: 1 }, name: '_id_' }
},
{
name: 'users',
type: 'collection',
options: {},
info: {
readOnly: false,
uuid: UUID("9523db08-3f73-4961-8cdc-4f3f63232cc9")
},
idIndex: { v: 2, key: { _id: 1 }, name: '_id_' }
}
]
Additional Collection Schemas
Additionally, should you want to enforce what kind of objects can be inserted in your collection, optional schemas can also be used with MongoDB.
Schemas are JSON-like objects which define the type for the objects that can be stored inside the collection.
For example, to create a collection called validCars in which the manufacturer and model needs to be always stored, this kind of syntax can be used: