1) MongoDB: Create Database, Collection, and Insert Multiple Documents
To perform fundamental operations in MongoDB, such as creating a database, a collection, and
inserting multiple documents, the MongoDB shell or a MongoDB client (like Compass or a [Link]
driver) can be used. Here's how each operation is handled:
1. **Creating a Database:**
MongoDB automatically creates a database when data is inserted into it. You can switch to the
desired database using:
```js
use myDatabase
```
2. **Creating a Collection:**
Collections are created when you insert the first document into them, but they can also be explicitly
created:
```js
[Link]("products")
```
3. **Inserting Multiple Documents:**
You can insert multiple documents into a collection using `insertMany()`:
```js
[Link]([
{ name: "Laptop", category: "Electronics", price: 1200, stock: 20 },
{ name: "Keyboard", category: "Electronics", price: 100, stock: 50 },
{ name: "Chair", category: "Furniture", price: 150, stock: 15 },
{ name: "Notebook", category: "Stationery", price: 5, stock: 200 }
])
```
Each document is a JSON-like object that MongoDB stores internally in BSON format. The `_id` field
is automatically generated unless specified. MongoDBs flexibility allows different documents within
the same collection to have different fields or structures.
These basic operations form the foundation of MongoDB data handling. Combined with powerful
querying, indexing, and aggregation capabilities, MongoDB offers robust support for modern,
scalable applications.