Collection in MongoDB:
In MongoDB, a collection is a grouping of MongoDB documents.
It is the equivalent of a table in a relational database system.
Collections store documents in a structured format, and each document can have its own unique structure.
Collections in MongoDB are schema-less, meaning that different documents within the same collection can have different fields and structures.
To create a collection in the MongoDB Shell, you can use the db.createCollection() method. Here's an example:
Start the MongoDB Shell by running the mongo command in your terminal or command prompt.
- Connect to the MongoDB server by specifying the connection string. For example:
mongo mongodb://localhost:27017
- Switch to the desired database where you want to create the collection using the
use
command. For example:
use mydatabase
- Use the
db.createCollection()
method to create a collection. Provide the name of the collection you want to create as an argument. For example:
db.createCollection("mycollection")
This will create a collection named "mycollection" in the current database. You can replace "mycollection" with the desired name for your collection.
If you want to specify additional options while creating the collection, you can pass them as an object as the second argument to createCollection()
. For example:
db.createCollection("mycollection", { capped: true, size: 1048576, max: 1000 })
In this case, the collection will be created as a capped collection with a maximum size of 1 MB (size: 1048576
) and a maximum document count of 1000 (max: 1000
).
Remember to switch to the appropriate database using the use
command before executing the db.createCollection()
method.
- Also you can create a collection by inserting a document into it.
- Collections in MongoDB are created implicitly when the first document is inserted.
- For example, to create a collection named "mycollection" and insert a document into it,
- run the following commands:
db.mycollection.insertOne({ key: "value" })
This will create the "mycollection" collection and insert a document with the field "key" set to "value."
If the collection already exists, MongoDB will simply insert the document into the existing collection.
0 Comments