Podręcznik użytkownika MongoDB
Podstawowe pojęcia
Baza danych
Baza danych to najwyższy poziom kontenera danych w MongoDB. Każda baza danych ma własne kolekcje i ustawienia uprawnień. W MongoDB można utworzyć wiele baz danych, z których każda jest niezależna od pozostałych.
Kolekcja
Kolekcja to grupa dokumentów MongoDB, podobna do tabeli w relacyjnej bazie danych. Dokumenty w kolekcji mogą mieć różne pola, co czyni kolekcje bardzo elastycznymi. W przeciwieństwie do relacyjnych baz danych, kolekcje nie wymuszają sztywnego, z góry zdefiniowanego schematu.
Dokument
Dokument to podstawowa jednostka danych w MongoDB, składająca się z par pól i wartości. Dokumenty są podobne do obiektów JSON i są przechowywane w formacie BSON (Binary JSON).
BSON to binarna reprezentacja dokumentów JSON z dodatkową obsługą typów danych. Maksymalny rozmiar dokumentu to 16 MB.
Połącz się z MongoDB
Połącz się z lokalną bazą danych za pomocą mongosh
mongosh
Połącz się ze zdalną bazą danych
mongosh "mongodb://hostname:port"
Połącz się za pomocą parametru połączenia z uwierzytelnianiem
mongosh "mongodb://username:password@hostname:port/database?authSource=admin"
Połącz się za pomocą URI
mongosh "mongodb://localhost:27017,mongodb://localhost:27018/?replicaSet=myReplSet"
Operacje na bazach danych
Wyświetl bazy danych
show dbs
Przełącz/utwórz bazę danych
use mydatabase
Uwaga: Podczas przełączania baz danych za pomocą polecenia use, jeśli baza danych nie istnieje, MongoDB ją utworzy, ale nie zostanie ona naprawdę utworzona, dopóki nie wstawisz dokumentów.
Wyświetl informacje o bieżącej bazie danych
db.stats()
Usuń bazę danych
db.dropDatabase()
Operacje na kolekcjach
Wyświetl kolekcje
show collections
Utwórz kolekcję
db.createCollection("mycollection")
Utwórz kolekcję z opcjami
db.createCollection("mycollection", {
capped: true,
size: 1000000,
max: 100
})
Usuń kolekcję
db.mycollection.drop()
Wyświetl statystyki kolekcji
db.mycollection.stats()
Wstawianie dokumentów
MongoDB udostępnia następujące metody wstawiania dokumentów do kolekcji:
Wstaw pojedynczy dokument
db.users.insertOne({
name: "John",
age: 30,
email: "[email protected]",
address: {
city: "New York",
street: "Main Street"
},
hobbies: ["basketball", "swimming"]
})
Wstaw wiele dokumentów
db.users.insertMany([
{ name: "Jane", age: 25, city: "Los Angeles" },
{ name: "Bob", age: 35, city: "Chicago" },
{ name: "Alice", age: 28, city: "San Francisco" }
])
Wstaw dokument (przestarzałe, ale dostępne)
db.users.insert({
name: "David",
age: 32
})
Wyświetl wynik wstawiania
# View inserted document ID
db.users.insertOne({ name: "Test" })
# Returns: { acknowledged: true, insertedId: ObjectId("...") }
Zapytania o dokumenty
Zapytaj o wszystkie dokumenty
db.users.find()
To jest równoważne z SELECT * FROM users w SQL.
Zapytaj o pojedynczy dokument
db.users.findOne()
Zapytania z warunkami
# Equality query
db.users.find({ age: 30 })
# Not equal query
db.users.find({ age: { $ne: 30 } })
# Greater than query
db.users.find({ age: { $gt: 25 } })
# Greater than or equal query
db.users.find({ age: { $gte: 25 } })
# Less than query
db.users.find({ age: { $lt: 30 } })
# Less than or equal query
db.users.find({ age: { $lte: 30 } })
# Range query
db.users.find({ age: { $gte: 20, $lte: 30 } })
Operatory logiczne
# AND (default)
db.users.find({ age: { $gte: 25 }, name: "Jane" })
# OR
db.users.find({ $or: [{ age: { $gte: 30 } }, { name: "Bob" }] })
# NOR (neither nor)
db.users.find({ $nor: [{ age: { $lt: 20 } }, { city: "New York" }] })
# NOT
db.users.find({ age: { $not: { $gte: 25 } } })
Zapytania o tablice
# Array contains element
db.users.find({ hobbies: "basketball" })
# Array contains all elements
db.users.find({ hobbies: { $all: ["basketball", "swimming"] } })
# Array length
db.users.find({ hobbies: { $size: 2 } })
# Array element at specific position
db.users.find({ "hobbies.0": "basketball" })
# Array element matching condition
db.users.find({ hobbies: { $elemMatch: { $eq: "basketball" } } })
Zapytania o zagnieżdżone dokumenty
# Nested document field query
db.users.find({ "address.city": "New York" })
# Complete nested document match
db.users.find({ address: { city: "New York", street: "Main Street" } })
Projekcja (zwracanie tylko określonych pól)
# Return only name and email fields
db.users.find({ age: 30 }, { name: 1, email: 1 })
# Exclude a field
db.users.find({}, { age: 0 })
# Return all fields except _id
db.users.find({}, { _id: 0 })
Sortowanie
# Sort by age ascending
db.users.find().sort({ age: 1 })
# Sort by age descending
db.users.find().sort({ age: -1 })
# Multi-field sort
db.users.find().sort({ age: -1, name: 1 })
Limit i pominięcie
# Return first 5 documents
db.users.find().limit(5)
# Skip first 10 documents, return next 5 (pagination)
db.users.find().skip(10).limit(5)
# Count documents
db.users.countDocuments({ age: { $gte: 25 } })
# Estimate collection document count (fast but may be inaccurate)
db.users.estimatedDocumentCount()
Operacje na kursorze
# Use cursor
var cursor = db.users.find()
while (cursor.hasNext()) {
printjson(cursor.next())
}
# forEach iteration
db.users.find().forEach(function(doc) {
print("Name: " + doc.name)
})
Aktualizacja dokumentów
Zaktualizuj pojedynczy dokument
db.users.updateOne(
{ name: "John" },
{ $set: { age: 31 } }
)
Zaktualizuj wiele dokumentów
db.users.updateMany(
{ age: { $lt: 30 } },
{ $set: { status: "young" } }
)
Zastąp dokument
db.users.replaceOne(
{ name: "John" },
{ name: "John", age: 32, email: "[email protected]", city: "Boston" }
)
Operatory aktualizacji
# $set - Set field value
db.users.updateOne({ name: "Jane" }, { $set: { age: 26 } })
# $unset - Remove field
db.users.updateOne({ name: "Jane" }, { $unset: { email: "" } })
# $inc - Increment/decrement
db.users.updateOne({ name: "Jane" }, { $inc: { age: 1 } })
db.users.updateOne({ name: "Jane" }, { $inc: { age: -1 } })
# $rename - Rename field
db.users.updateOne({ name: "Jane" }, { $rename: { "name": "fullname" } })
# $mul - Multiply
db.users.updateOne({ name: "Jane" }, { $mul: { age: 2 } })
# $min - Set minimum value
db.users.updateOne({ name: "Jane" }, { $min: { age: 20 } })
# $max - Set maximum value
db.users.updateOne({ name: "Jane" }, { $max: { age: 40 } })
# $push - Add element to array
db.users.updateOne({ name: "Jane" }, { $push: { hobbies: "running" } })
# $pull - Remove matching elements from array
db.users.updateOne({ name: "Jane" }, { $pull: { hobbies: "swimming" } })
# $addToSet - Add element to array (no duplicates)
db.users.updateOne({ name: "Jane" }, { $addToSet: { hobbies: "basketball" } })
# $pop - Remove first or last element from array
db.users.updateOne({ name: "Jane" }, { $pop: { hobbies: 1 } })
Operacja upsert
# Insert if not exists, update if exists
db.users.updateOne(
{ name: "New User" },
{ $set: { age: 25, city: "Seattle" } },
{ upsert: true }
)
Usuwanie dokumentów
Usuń pojedynczy dokument
db.users.deleteOne({ name: "John" })
Usuń wiele dokumentów
db.users.deleteMany({ age: { $lt: 20 } })
Usuń wszystkie dokumenty
db.users.deleteMany({})
Potok agregacji
Potok agregacji jest jedną z najpotężniejszych funkcji MongoDB, używaną do przetwarzania strumieni danych oraz wykonywania złożonych transformacji i analiz danych.
Podstawowa składnia
db.collection.aggregate([
{ $stage1: { ... } },
{ $stage2: { ... } },
...
])
Typowe etapy agregacji
$match - Filtruj dokumenty
db.users.aggregate([
{ $match: { age: { $gte: 25 } } }
])
$project - Projekcja
db.users.aggregate([
{ $project: { _id: 0, name: 1, age: 1 } }
])
$group - Grupuj
# Count users by age
db.users.aggregate([
{ $group: { _id: "$age", count: { $sum: 1 } } }
])
# Calculate average age
db.users.aggregate([
{ $group: { _id: null, avgAge: { $avg: "$age" } } }
])
# Group and collect names
db.users.aggregate([
{ $group: { _id: "$city", users: { $push: "$name" } } }
])
$sort - Sortuj
db.users.aggregate([
{ $sort: { age: -1, name: 1 } }
])
$limit - Ogranicz liczbę
db.users.aggregate([
{ $limit: 5 }
])
$skip - Pomiń dokumenty
db.users.aggregate([
{ $skip: 10 },
{ $limit: 5 }
])
$unwind - Rozłóż tablicę
db.users.aggregate([
{ $unwind: "$hobbies" }
])
$lookup - Złącz kolekcje
# Assuming two collections: orders and products
db.orders.aggregate([
{
$lookup: {
from: "products",
localField: "productId",
foreignField: "_id",
as: "productDetails"
}
}
])
Operatory agregacji
Operatory arytmetyczne
db.sales.aggregate([
{
$project: {
total: { $add: ["$price", "$tax"] },
discount: { $multiply: ["$price", 0.1] }
}
}
])
Operatory łańcuchów
db.users.aggregate([
{
$project: {
fullName: { $concat: ["$firstName", " ", "$lastName"] },
upperName: { $toUpper: "$name" }
}
}
])
Operatory dat
db.users.aggregate([
{
$project: {
year: { $year: "$birthdate" },
month: { $month: "$birthdate" },
day: { $dayOfMonth: "$birthdate" }
}
}
])
Kompletny przykład
# Find the top three airlines with the most direct flights out of PDX
db.routes.aggregate([
{
$match: {
"src_airport": "PDX",
"stops": 0
}
},
{
$group: {
_id: "$airline.name",
count: { $sum: 1 }
}
},
{
$sort: { count: -1 }
},
{
$limit: 3
}
])
Indeksy
Indeksy wspierają wydajne wykonywanie zapytań w MongoDB. Bez indeksów MongoDB musi przeskanować każdy dokument w kolekcji, aby zwrócić wyniki zapytania.
Tworzenie indeksów
# Single field index
db.users.createIndex({ name: 1 })
# Descending index
db.users.createIndex({ age: -1 })
# Compound index
db.users.createIndex({ age: 1, name: 1 })
# Unique index
db.users.createIndex({ email: 1 }, { unique: true })
# Text index
db.users.createIndex({ description: "text" })
# Multikey index (array field)
db.users.createIndex({ hobbies: 1 })
# Geospatial index
db.locations.createIndex({ location: "2dsphere" })
# Hashed index
db.users.createIndex({ _id: "hashed" })
Wyświetlanie indeksów
# View all indexes on a collection
db.users.getIndexes()
# View index size
db.users.totalIndexSize()
Usuwanie indeksów
# Drop specified index
db.users.dropIndex("name_1")
# Drop all indexes (except _id index)
db.users.dropIndexes()
# Drop text index
db.users.dropIndex("description_text")
Właściwości indeksów
# Sparse index (only indexes non-null values)
db.users.createIndex({ email: 1 }, { sparse: true })
# Partial index
db.users.createIndex(
{ email: 1 },
{ partialFilterExpression: { email: { $exists: true } } }
)
# TTL index (automatic expiration)
db.sessions.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 3600 }
)
Zalecenia dotyczące strategii indeksowania
- Twórz indeksy na polach często używanych w warunkach zapytań
- Kolejność pól w indeksach złożonych ma znaczenie: umieść pola dokładnego dopasowania na początku, a pola zapytań zakresowych na końcu
- Unikaj tworzenia zbyt wielu indeksów w kolekcjach o wysokiej częstotliwości zapisu
- Użyj explain(), aby analizować wydajność zapytań
Analiza zapytań
# Analyze query
db.users.find({ age: 25 }).explain()
# Analyze execution plan
db.users.find({ age: { $gte: 25 } }).sort({ name: 1 }).explain("executionStats")
Operacje na zestawie replik
Zestaw replik to grupa instancji MongoDB, które utrzymują ten sam zbiór danych, zapewniając redundancję i wysoką dostępność.
Zainicjuj zestaw replik
rs.initiate()
Wyświetl status zestawu replik
rs.status()
Wyświetl konfigurację zestawu replik
rs.conf()
Dodaj członka wtórnego
rs.add("hostname:27017")
Dodaj arbitera
rs.addArb("hostname:27017")
Usuń członka
rs.remove("hostname:27017")
Wybory w zestawie replik
Gdy serwer główny jest niedostępny, zestaw replik automatycznie przeprowadza wybory. Możesz wywołać wybory za pomocą:
# Force current node to become primary (use in specific situations)
rs.stepDown()
Preferencja odczytu
# Read from primary (default)
db.getMongo().setReadPref("primary")
# Read from secondary
db.getMongo().setReadPref("secondary")
# Read from nearest node
db.getMongo().setReadPref("nearest")
Operacje shardingu
Sharding to podejście MongoDB do skalowania poziomego, polegające na rozdzielaniu danych na wiele serwerów.
Włącz sharding
sh.enableSharding("mydatabase")
Sharduj kolekcję
sh.shardCollection("mydatabase.mycollection", { _id: 1 })
Wyświetl status shardingu
sh.status()
Dodaj shard
sh.addShard("shard_replica_set/hostname:27017")
Import i eksport danych
Korzystanie z mongodump i mongorestore
Eksport danych
# Export entire database
mongodump --db=mydatabase --out=/backup
# Export specific collection
mongodump --db=mydatabase --collection=users --out=/backup
# Export with compression
mongodump --db=mydatabase --gzip --out=/backup
Import danych
# Restore entire database
mongorestore --db=mydatabase /backup/mydatabase
# Restore specific collection
mongorestore --db=mydatabase --collection=users /backup/mydatabase/users.bson
# Restore with compression
mongorestore --db=mydatabase --gzip /backup/mongodb
Korzystanie z mongoexport i mongoimport
Eksport jako JSON
# Export as JSON
mongoexport --db=mydatabase --collection=users --out=users.json
# Export as JSON array
mongoexport --db=mydatabase --collection=users --out=users.json --jsonArray
# Export CSV
mongoexport --db=mydatabase --collection=users --out=users.csv --fields=name,age,email
Import z JSON
# Import from JSON
mongoimport --db=mydatabase --collection=users --file=users.json
# Import from JSON array
mongoimport --db=mydatabase --collection=users --file=users.json --jsonArray
# Import from CSV
mongoimport --db=mydatabase --collection=users --file=users.csv --headerline
Typowe polecenia administracyjne
Wyświetl status serwera
db.serverStatus()
Wyświetl status bieżącej bazy danych
db.stats()
Wyświetl statystyki kolekcji
db.users.stats()
Wyświetl bieżące operacje
db.currentOp()
Wyświetl wolne zapytania
# View recent slow queries
db.system.profile.find().sort({ ts: -1 }).limit(10)
Wymuś zamknięcie bazy danych
# Use in emergencies only
db.adminCommand({ shutdown: 1 })
Operacje transakcyjne
MongoDB 4.0+ obsługuje wielodokumentowe transakcje.
Podstawowa transakcja
session = db.getMongo().startSession()
session.startTransaction({ readConcern: { level: "snapshot" }, writeConcern: { w: "majority" } })
try {
session.getDatabase("mydb").accounts.updateOne(
{ accountId: 1 },
{ $inc: { balance: -100 } }
)
session.getDatabase("mydb").accounts.updateOne(
{ accountId: 2 },
{ $inc: { balance: 100 } }
)
session.commitTransaction()
} catch (error) {
session.abortTransaction()
throw error
} finally {
session.endSession()
}
Strumienie zmian
Strumienie zmian pozwalają aplikacjom nasłuchiwać zmian danych w czasie rzeczywistym.
# Listen for collection changes
var changeStream = db.users.watch()
while (changeStream.hasNext()) {
printjson(changeStream.next())
}
GridFS
GridFS służy do przechowywania dużych plików przekraczających limit 16 MB.
# Upload file
mongofiles put myfile.txt
# List files
mongofiles list
# Download file
mongofiles get myfile.txt
# Delete file
mongofiles delete myfile.txt
