Understanding Databases
Understanding databases in MongoDB
In MongoDB, a database is a physical container for collections. Each database contains its own set of files on the file system. A single MongoDB server can have multiple databases, and each database can have multiple collections.
Creating a Database
Databases are created implicitly when the first collection is created. However, you can switch to a database explicitly using the use
command.
Switch Database Command
use myDatabase
Key Features of Databases
Some key features of databases in MongoDB include:
- Isolation: Each database is isolated from others, providing data segregation.
- Separate File Storage: Each database has its own set of files, allowing for independent management of storage.
- Multiple Databases: A single MongoDB server instance can support multiple databases, useful for multi-tenant applications.
Example: Creating and Using a Database
Below is an example of creating a database and adding collections to it:
Commands
// Switching to a new database use companyDB // Creating a collection db.createCollection("employees") // Inserting documents db.employees.insertMany([ { name: "Alice", age: 28, position: "Manager" }, { name: "Bob", age: 24, position: "Engineer" }, { name: "Charlie", age: 35, position: "CEO" } ]) // Querying the collection db.employees.find({ position: "Engineer" })