To create a database and a collection in MongoDB, you need to follow the following steps:
1. Start by opening up the MongoDB shell by running the command ‘mongo‘ in your terminal. This will launch the MongoDB shell and connect to the default ‘test‘ database.
2. To create a new database, you can use the ‘use‘ command followed by the name of the new database you want to create. For example, to create a new database called ‘mydb‘, run the following command:
use mydb
Note that this command will not create the database until you create a collection.
3. To create a collection, you can use the ‘db.createCollection()‘ method. For example, to create a new collection called ‘mycollection‘ in the ‘mydb‘ database, run the following command:
db.createCollection("mycollection")
By default, MongoDB does not enforce any schema on the collections that it creates. However, you can add constraints on the fields of the documents using validators or indexes.
Here is an example that shows how to create a collection with validators applied to its fields:
db.runCommand({
create: "students",
validator: {
$jsonSchema: {
bsonType: "object",
required: [ "name", "age", "courses" ],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
age: {
bsonType: "int",
minimum: 18,
maximum: 30,
description: "must be an integer in the range 18-30"
},
courses: {
bsonType: "array",
items: {
bsonType: "string",
description: "must be a string"
}
}
}
}
}
})
This ‘db.runCommand()‘ example creates the ‘students‘ collection with the following validators on its fields:
- ‘name‘: must be a string and is required.
- ‘age‘: must be an integer in the range 18-30.
- ‘courses‘: must be an array of strings.
By applying validators like this, we can ensure that the data stored in MongoDB is consistent and can also help prevent malicious attacks that may try to inject data that violates the schema constraints.