MongoDB – Create Collection:
In mongoDB, Collection is nothing but a container of all documents.It is almost equivalent to table in RDBMS which is a combination of rows and columns. We can Create collections by using the below syntax.
1 |
<strong>Syntax:</strong>db.createCollections(name, options) |
Parameter | Type | Description |
---|---|---|
Name | string | Name of the collection |
Options | document | Optional. Configuration options for creating a capped collection, for pre-allocating space in a new collection, or for creating a view. |
Example:
Use the test database and verify the database in which you are in.
1 2 3 |
testset:PRIMARY> use test switched to db test testset:PRIMARY>db test |
Create collection called “i2tutorial” by using below command
1 2 |
testset:PRIMARY>db.createCollection("i2tutorial") { "ok" : 1 } |
Check the collection which you created.
1 2 3 4 |
testset:PRIMARY> show collections i2tutorial mycollection system.indexes |
Also, you can create collections automatically by inserting a document into it.
1 2 3 4 5 |
<strong>Example:</strong> testset:PRIMARY> show collections i2tutorial mycollection system.indexes |
Insert the data into the collection called ” imongo”
1 2 |
testset:PRIMARY>db.imongo.insert({"name":"maria","city":"Banglore"}) WriteResult({ "nInserted" : 1 }) |
Check if the collection imongo and the data inserted exists or not.
1 2 3 4 5 6 7 |
testset:PRIMARY> show collections i2tutorial imongo mycollection system.indexes testset:PRIMARY>db.imongo.find() { "_id" : ObjectId("5924462a5273c93ad95b109a"), "name" : "maria", "city" : "Banglore" } |