Google:

adverisment

MongoDB tutorial

details img

Installing MongoDB

1. Installation

  • Windows, macOS, Linux: Download from the official MongoDB website.
  • Use package managers for installation:
    • Ubuntu: sudo apt install -y mongodb
    • macOS: brew install mongodb-community

2. Starting the MongoDB Server

  • Run: mongod
  • Access the MongoDB shell: mongo

Basic MongoDB Operations

Here are the essentials for getting started:

1. Databases

  • Show all databases: show dbs
  • Switch/Create a database: use <database_name>

2. Collections

Collections are similar to tables in relational databases.

  • Show collections: show collections
  • Create a collection: Automatically created when you insert the first document.

3. Documents

Documents are JSON-like objects stored in collections.

Example Document:

json
{ "name": "John Doe", "age": 30, "hobbies": ["reading", "gaming"] }

4. CRUD Operations

Create

Insert a document:

javascript
db.collection_name.insertOne({ "name": "Alice", "age": 25 });

Read

Find all documents:

javascript
db.collection_name.find();

Find with a condition:

javascript
db.collection_name.find({ "age": { "$gt": 20 } });

Update

Update a document:

javascript
db.collection_name.updateOne( { "name": "Alice" }, { "$set": { "age": 26 } } );

Delete

Delete a document:

javascript
db.collection_name.deleteOne({ "name": "Alice" });

Indexing

Indexes improve query performance. Create an index on a field:

javascript
db.collection_name.createIndex({ "age": 1 }); // Ascending order

Aggregation Framework

Perform complex queries:

javascript
db.collection_name.aggregate([ { "$match": { "age": { "$gt": 20 } } }, { "$group": { "_id": "$age", "count": { "$sum": 1 } } } ]);

Connection with Programming Languages

Use MongoDB drivers (e.g., Node.js, Python, Java):

Example in Python (using PyMongo):

python
from pymongo import MongoClient client = MongoClient("mongodb://localhost:27017/") db = client["mydatabase"] collection = db["mycollection"] # Insert a document collection.insert_one({"name": "Bob", "age": 28}) # Query documents for doc in collection.find({"age": {"$gt": 20}}): print(doc)

Leave Comment