To create a collection in MongoDB, we generally don't need to create one explicitly. Collections are created automatically when we insert documents into them.
However, if we want to ensure that a collection is created or we want to create an empty collection explicitly, we can do so using the MongoDB client or a MongoDB shell.
Here's how we can create a collection in MongoDB:
Before creating a Collection/table in MongoDB, First, we need to connect to our MongoDB instance using the MongoDB shell or a MongoDB client library using our programming language.
Using the Mongo shell, we can connect to a MongoDB server running on localhost by simply typing the `mongo` command in our terminal.
mongo
Once our connection is established successfully, we can check databases in MongoDB using the below command:
show dbs;
Switch to the database where you want to create the collection using the "use" command.
use your_database_name;
To check the current database name using mongo shell.
db
Use the "createCollection()" method to explicitly create a collection.
db.createCollection("your_collection_name")
# Connect to MongoDB (assuming it's running locally on the default port) mongo # Switch to the desired database use your_database_name # Create a collection named your_collection_name db.createCollection("your_collection_name")
The above command will create a collection in our specified Database.
We can also specify additional options when creating the collection, such as specifying the validation rules for documents in the collection or setting the size and maximum number of documents allowed in the collection.
# Create a collection named "your_collection_name" with options db.createCollection("your_collection_name", { validator: { $jsonSchema: { bsonType: "object", required: [ "name", "age" ], properties: { name: { bsonType: "string", description: "must be a string and is required" }, age: { bsonType: "int", description: "must be an integer and is required" } } }}, validationLevel: "strict", validationAction: "error" })
The above Statement will create a collection named "your_collection_name" with validation rules that require documents to have a name field of type string and an age field of type integer.
It also specifies that documents violating these rules should result in an error.
We have created a collection named `your_collection_name` and we have added validation on `age` and `name` as required.
db.your_collection_name.insertOne({ name: "Alice Collin", age: 20 })
{ acknowledged: true, insertedId: ObjectId('332bcb7eac36be0e09f4cf4s') }
Checking schema validation by just passing one value at a time.
# Run one Query at a time db.your_collection_name.insertOne({ name: "Alice Collin" }) db.your_collection_name.insertOne({ age: 20 })
MongoServerError: Document failed validation
In Both cases, we are getting the same error while inserting incorrect document data into the collection.