MongoDB NoSQL Installation
MongoDB: NoSQL-Datenbank
MongoDB ist eine dokumentenorientierte NoSQL-Datenbank. Statt Tabellen speichert sie flexible JSON-ähnliche Dokumente - ideal für agile Entwicklung und unstrukturierte Daten.
Installation
# MongoDB GPG Key
curl -fsSL https://pgp.mongodb.com/server-7.0.asc | sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-7.0.gpg
# Repository hinzufügen
echo "deb [ signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
# Installieren
sudo apt update
sudo apt install -y mongodb-org
# Starten
sudo systemctl start mongod
sudo systemctl enable mongod
Mongo Shell
# Shell starten
mongosh
# Datenbank wechseln/erstellen
use meine_datenbank
# Datenbanken anzeigen
show dbs
# Collections anzeigen
show collections
CRUD-Operationen
Create
// Einzelnes Dokument
db.users.insertOne({
name: "Max",
email: "max@example.com",
age: 30,
tags: ["developer", "admin"]
})
// Mehrere Dokumente
db.users.insertMany([
{ name: "Anna", email: "anna@example.com", age: 25 },
{ name: "Tom", email: "tom@example.com", age: 35 }
])
Read
// Alle Dokumente
db.users.find()
// Mit Filter
db.users.find({ age: { $gt: 25 } })
// Ein Dokument
db.users.findOne({ email: "max@example.com" })
// Projektion (nur bestimmte Felder)
db.users.find({}, { name: 1, email: 1, _id: 0 })
// Sortieren und Limit
db.users.find().sort({ age: -1 }).limit(5)
Update
// Ein Dokument
db.users.updateOne(
{ email: "max@example.com" },
{ $set: { age: 31 } }
)
// Mehrere Dokumente
db.users.updateMany(
{ age: { $lt: 30 } },
{ $set: { status: "young" } }
)
// Feld zum Array hinzufügen
db.users.updateOne(
{ name: "Max" },
{ $push: { tags: "senior" } }
)
Delete
// Ein Dokument
db.users.deleteOne({ name: "Tom" })
// Mehrere Dokumente
db.users.deleteMany({ age: { $gt: 50 } })
// Alle löschen
db.users.deleteMany({})
Query-Operatoren
| Operator | Bedeutung |
|---|---|
$eq |
Gleich |
$gt / $gte |
Größer (oder gleich) |
$lt / $lte |
Kleiner (oder gleich) |
$in |
In Array enthalten |
$and / $or |
Logische Verknüpfung |
$regex |
Regular Expression |
Indexe
// Index erstellen
db.users.createIndex({ email: 1 })
// Unique Index
db.users.createIndex({ email: 1 }, { unique: true })
// Compound Index
db.users.createIndex({ name: 1, age: -1 })
// Indexe anzeigen
db.users.getIndexes()
Node.js Integration
// npm install mongodb
const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
async function main() {
await client.connect();
const db = client.db('meine_datenbank');
const users = db.collection('users');
// Insert
await users.insertOne({ name: 'Max', age: 30 });
// Find
const result = await users.find({ age: { $gt: 25 } }).toArray();
console.log(result);
await client.close();
}
main();
Weitere Hilfe
- 📖 MongoDB Dokumentation
- 📧 E-Mail: support@enjyn.de