In this tutorial, we will guide you through the basics of MongoDB, a popular NoSQL database. We will show you how to install MongoDB, create collections and documents, and perform basic CRUD operations.
By the end of this tutorial, you will be able to:
Prerequisites: Basic knowledge of databases and JavaScript would be helpful.
After installation, you can interact with MongoDB using the MongoDB shell, an interactive JavaScript interface.
MongoDB organizes data into:
use
command to switch to a database. If the database doesn't exist, MongoDB will create it.Use the db.createCollection("collectionName")
command to create a collection.
Inserting Documents
Use the db.collectionName.insert(document)
command to insert a document into a collection.
Reading Documents
Use the db.collectionName.find()
command to find documents in a collection.
Updating Documents
Use the db.collectionName.update(query, update)
command to update documents.
Deleting Documents
db.collectionName.remove(query)
command to delete documents.// Create a 'users' collection.
db.createCollection("users")
```
Inserting Documents
javascript
// Insert a document into the 'users' collection.
db.users.insert({
name: "John Doe",
email: "johndoe@example.com",
age: 30
})
Reading Documents
javascript
// Find all documents in the 'users' collection.
db.users.find()
Updating Documents
javascript
// Update the 'age' field of the document where the 'name' is 'John Doe'.
db.users.update(
{ name: "John Doe" },
{ $set: { age: 31 } }
)
Deleting Documents
javascript
// Delete the document where the 'name' is 'John Doe'.
db.users.remove({ name: "John Doe" })
We have covered how to install and set up MongoDB, understand its basic structure, and perform CRUD operations. The next step is to learn how to create complex queries and use MongoDB in a programming language, such as JavaScript or Python.
For additional resources, check out the official MongoDB documentation.
Exercise: Create a 'products' collection and insert a document.
Solution:
javascript
use test
db.createCollection("products")
db.products.insert({
name: "iPhone",
price: 699
})
Exercise: Update the 'price' of the 'iPhone'.
Solution:
javascript
db.products.update(
{ name: "iPhone" },
{ $set: { price: 799 } }
)
Exercise: Delete the 'iPhone' document.
Solution:
javascript
db.products.remove({ name: "iPhone" })
Keep practicing and try to create and manage your own databases and collections!