Manuale utente di MongoDB

Concetti di base

Database

Un database è il contenitore di livello superiore per i dati in MongoDB. Ogni database ha le proprie collezioni e impostazioni di autorizzazione. Puoi creare più database in MongoDB, ciascuno indipendente dagli altri.

Collezione

Una collezione è un gruppo di documenti MongoDB, simile a una tabella in un database relazionale. I documenti in una collezione possono avere campi diversi, rendendo le collezioni molto flessibili. A differenza dei database relazionali, le collezioni non impongono uno schema rigido e predefinito.

Documento

Un documento è l'unità di dati di base in MongoDB, composta da coppie di campo e valore. I documenti sono simili agli oggetti JSON e sono memorizzati utilizzando il formato BSON (Binary JSON).

BSON è la rappresentazione binaria dei documenti JSON, con supporto aggiuntivo per i tipi di dati. La dimensione massima di un documento è 16 MB.

Connettersi a MongoDB

Connettersi al database locale usando mongosh

mongosh

Connettersi al database remoto

mongosh "mongodb://hostname:port"

Connettersi usando la stringa di connessione con autenticazione

mongosh "mongodb://username:password@hostname:port/database?authSource=admin"

Connettersi usando URI

mongosh "mongodb://localhost:27017,mongodb://localhost:27018/?replicaSet=myReplSet"

Operazioni sul database

Visualizzare i database

show dbs

Cambiare/creare un database

use mydatabase

Nota: quando cambi database con il comando use, se il database non esiste, MongoDB lo crea, ma non sarà realmente creato finché non inserisci dei documenti.

Visualizzare le informazioni del database corrente

db.stats()

Eliminare un database

db.dropDatabase()

Operazioni sulle collezioni

Visualizzare le collezioni

show collections

Creare una collezione

db.createCollection("mycollection")

Creare una collezione con opzioni

db.createCollection("mycollection", {
  capped: true,
  size: 1000000,
  max: 100
})

Eliminare una collezione

db.mycollection.drop()

Visualizzare le statistiche della collezione

db.mycollection.stats()

Inserire documenti

MongoDB fornisce i seguenti metodi per inserire documenti in una collezione:

Inserire un singolo documento

db.users.insertOne({
  name: "John",
  age: 30,
  email: "[email protected]",
  address: {
    city: "New York",
    street: "Main Street"
  },
  hobbies: ["basketball", "swimming"]
})

Inserire più documenti

db.users.insertMany([
  { name: "Jane", age: 25, city: "Los Angeles" },
  { name: "Bob", age: 35, city: "Chicago" },
  { name: "Alice", age: 28, city: "San Francisco" }
])

Inserire un documento (deprecato ma disponibile)

db.users.insert({
  name: "David",
  age: 32
})

Visualizzare il risultato dell'inserimento

# View inserted document ID
db.users.insertOne({ name: "Test" })
# Returns: { acknowledged: true, insertedId: ObjectId("...") }

Interrogare i documenti

Interrogare tutti i documenti

db.users.find()

Questo equivale a SELECT * FROM users in SQL.

Interrogare un singolo documento

db.users.findOne()

Interrogare con condizioni

# 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 } })

Operatori logici

# 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 } } })

Query sugli array

# 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" } } })

Query su documenti annidati

# 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" } })

Proiezione (restituire solo i campi specificati)

# 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 })

Ordinamento

# 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 })

Limite e salto

# 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()

Operazioni sul cursore

# 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)
})

Aggiornare documenti

Aggiornare un singolo documento

db.users.updateOne(
  { name: "John" },
  { $set: { age: 31 } }
)

Aggiornare più documenti

db.users.updateMany(
  { age: { $lt: 30 } },
  { $set: { status: "young" } }
)

Sostituire un documento

db.users.replaceOne(
  { name: "John" },
  { name: "John", age: 32, email: "[email protected]", city: "Boston" }
)

Operatori di aggiornamento

# $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 } })

Operazione di upsert

# Insert if not exists, update if exists
db.users.updateOne(
  { name: "New User" },
  { $set: { age: 25, city: "Seattle" } },
  { upsert: true }
)

Eliminare documenti

Eliminare un singolo documento

db.users.deleteOne({ name: "John" })

Eliminare più documenti

db.users.deleteMany({ age: { $lt: 20 } })

Eliminare tutti i documenti

db.users.deleteMany({})

Pipeline di aggregazione

La pipeline di aggregazione è una delle funzionalità più potenti di MongoDB, usata per elaborare flussi di dati ed eseguire complesse trasformazioni e analisi dei dati.

Sintassi di base

db.collection.aggregate([
  { $stage1: { ... } },
  { $stage2: { ... } },
  ...
])

Fasi di aggregazione comuni

$match - Filtrare i documenti

db.users.aggregate([
  { $match: { age: { $gte: 25 } } }
])

$project - Proiezione

db.users.aggregate([
  { $project: { _id: 0, name: 1, age: 1 } }
])

$group - Raggruppare

# 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 - Ordinare

db.users.aggregate([
  { $sort: { age: -1, name: 1 } }
])

$limit - Limitare il numero

db.users.aggregate([
  { $limit: 5 }
])

$skip - Saltare i documenti

db.users.aggregate([
  { $skip: 10 },
  { $limit: 5 }
])

$unwind - Scomporre gli array

db.users.aggregate([
  { $unwind: "$hobbies" }
])

$lookup - Unire le collezioni

# Assuming two collections: orders and products
db.orders.aggregate([
  {
    $lookup: {
      from: "products",
      localField: "productId",
      foreignField: "_id",
      as: "productDetails"
    }
  }
])

Operatori di aggregazione

Operatori aritmetici

db.sales.aggregate([
  {
    $project: {
      total: { $add: ["$price", "$tax"] },
      discount: { $multiply: ["$price", 0.1] }
    }
  }
])

Operatori di stringa

db.users.aggregate([
  {
    $project: {
      fullName: { $concat: ["$firstName", " ", "$lastName"] },
      upperName: { $toUpper: "$name" }
    }
  }
])

Operatori di data

db.users.aggregate([
  {
    $project: {
      year: { $year: "$birthdate" },
      month: { $month: "$birthdate" },
      day: { $dayOfMonth: "$birthdate" }
    }
  }
])

Esempio completo

# 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
  }
])

Indici

Gli indici supportano l'esecuzione efficiente delle query in MongoDB. Senza indici, MongoDB deve scansionare ogni documento in una collezione per restituire i risultati delle query.

Creare indici

# 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" })

Visualizzare gli indici

# View all indexes on a collection
db.users.getIndexes()

# View index size
db.users.totalIndexSize()

Eliminare gli indici

# 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")

Proprietà degli indici

# 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 }
)

Consigli sulla strategia di indicizzazione

  • Crea indici sui campi usati frequentemente nelle condizioni di query
  • L'ordine dei campi negli indici composti è importante: colloca prima i campi di corrispondenza esatta, e per ultimi i campi di query per intervallo
  • Evita di creare troppi indici su collezioni con alta frequenza di scrittura
  • Usa explain() per analizzare le prestazioni delle query

Analisi delle query

# Analyze query
db.users.find({ age: 25 }).explain()

# Analyze execution plan
db.users.find({ age: { $gte: 25 } }).sort({ name: 1 }).explain("executionStats")

Operazioni sui replica set

Un replica set è un gruppo di istanze MongoDB che mantengono lo stesso set di dati, fornendo ridondanza e alta disponibilità.

Inizializzare un replica set

rs.initiate()

Visualizzare lo stato del replica set

rs.status()

Visualizzare la configurazione del replica set

rs.conf()

Aggiungere un membro secondario

rs.add("hostname:27017")

Aggiungere un arbitro

rs.addArb("hostname:27017")

Rimuovere un membro

rs.remove("hostname:27017")

Elezioni del replica set

Quando il primario non è disponibile, il replica set conduce automaticamente un'elezione. Puoi attivare un'elezione con:

# Force current node to become primary (use in specific situations)
rs.stepDown()

Preferenza di lettura

# Read from primary (default)
db.getMongo().setReadPref("primary")

# Read from secondary
db.getMongo().setReadPref("secondary")

# Read from nearest node
db.getMongo().setReadPref("nearest")

Operazioni di sharding

Lo sharding è l'approccio di MongoDB alla scalabilità orizzontale, distribuendo i dati su più server.

Abilitare lo sharding

sh.enableSharding("mydatabase")

Shardare una collezione

sh.shardCollection("mydatabase.mycollection", { _id: 1 })

Visualizzare lo stato dello sharding

sh.status()

Aggiungere uno shard

sh.addShard("shard_replica_set/hostname:27017")

Importazione ed esportazione dei dati

Usando mongodump e mongorestore

Esportare i dati

# 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

Importare i dati

# 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

Usando mongoexport e mongoimport

Esportare come 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

Importare da 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

Comandi amministrativi comuni

Visualizzare lo stato del server

db.serverStatus()

Visualizzare lo stato del database corrente

db.stats()

Visualizzare le statistiche della collezione

db.users.stats()

Visualizzare le operazioni correnti

db.currentOp()

Visualizzare le query lente

# View recent slow queries
db.system.profile.find().sort({ ts: -1 }).limit(10)

Forzare l'arresto del database

# Use in emergencies only
db.adminCommand({ shutdown: 1 })

Operazioni transazionali

MongoDB 4.0+ supporta transazioni multi-documento.

Transazione di base

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()
}

Change Streams

I change stream consentono alle applicazioni di ascoltare le modifiche ai dati in tempo reale.

# Listen for collection changes
var changeStream = db.users.watch()
while (changeStream.hasNext()) {
  printjson(changeStream.next())
}

GridFS

GridFS è usato per memorizzare file di grandi dimensioni che superano il limite di 16 MB.

# Upload file
mongofiles put myfile.txt

# List files
mongofiles list

# Download file
mongofiles get myfile.txt

# Delete file
mongofiles delete myfile.txt