In MongoDB il metodo db.collection.find() seleziona i documenti di una collection o di una vista e restituisce un cursore sui documenti selezionati.
La parte collection è il nome della collection o della vista da interrogare.
Puoi usarlo per restituire tutti i documenti, solo alcuni o un unico documento, e puoi anche controllare quali campi vengono restituiti.
A rigore non restituisce i documenti stessi, ma un cursore verso di essi. Ciononostante, è comune dire che "restituisce documenti", e questo articolo segue tale convenzione 🙂
Restituire tutti i documenti
Ecco una rapida dimostrazione.
db.pets.find()
Risultato:
{ "_id" : 1, "name" : "Wag", "type" : "Dog", "weight" : 20 } { "_id" : 2, "name" : "Bark", "type" : "Dog", "weight" : 10 } { "_id" : 3, "name" : "Meow", "type" : "Cat", "weight" : 7 } { "_id" : 4, "name" : "Scratch", "type" : "Cat", "weight" : 8 } { "_id" : 5, "name" : "Bruce", "type" : "Bat", "weight" : 3 }
Qui find() restituisce tutti i documenti della collection pets. Sappiamo che restituisce tutto perché non abbiamo fornito alcun criterio di filtro, e in effetti nessun argomento. Chiamato senza argomenti, find() restituisce tutti i documenti e tutti i loro campi.
Un modo equivalente di scriverlo è:
db.pets.find({})
Qui passiamo un documento vuoto. Aggiungendo qualcosa al suo interno possiamo iniziare a filtrare i risultati.
Filtrare i risultati
La sintassi completa di find() è:
db.collection.find(query, projection)
Puoi quindi passare una query come primo argomento e una projection come secondo. Una query è un documento che contiene operatori di query; come abbiamo visto, un documento vuoto restituisce tutto.
Riduciamo i risultati a un sottoinsieme.
db.pets.find({"type":"Dog"})
Risultato:
{ "_id" : 1, "name" : "Wag", "type" : "Dog", "weight" : 20 } { "_id" : 2, "name" : "Bark", "type" : "Dog", "weight" : 10 }
Questo ha ristretto i risultati ai documenti il cui campo type è uguale a Dog. Qui abbiamo semplicemente passato un documento come filtro.
Puoi anche usare gli operatori di query per criteri piú specifici.
Esempio:
db.pets.find({"weight": { $lt: 10 }})
Risultato:
{ "_id" : 3, "name" : "Meow", "type" : "Cat", "weight" : 7 } { "_id" : 4, "name" : "Scratch", "type" : "Cat", "weight" : 8 } { "_id" : 5, "name" : "Bruce", "type" : "Bat", "weight" : 3 }
Documenti incorporati
Per i documenti che contengono documenti incorporati, puoi interrogare i dati annidati usando:
- La notazione con punto (ad esempio
field.nestedfield: <value>) - La forma annidata (ad esempio {
field: { nestedfield: <value> } }). Questa opzione è disponibile solo a partire da MongoDB 4.4.
Supponiamo di inserire il seguente documento.
db.pets.insertOne({ "_id" : 6, "name" : "Fetch", "type" : "Dog", "specs" : { "height" : 400, "weight" : 15, "color" : "brown" } })
Possiamo usare la notazione con punto per interrogare il documento incorporato.
db.pets.find({ "specs.height": 400 })
Risultato:
{ "_id" : 6, "name" : "Fetch", "type" : "Dog", "specs" : { "height" : 400, "weight" : 15, "color" : "brown" } }
Questa query restituisce lo stesso documento, ma fa riferimento al documento incorporato usando la forma annidata.
db.pets.find({ "specs" : { "height" : 400, "weight" : 15, "color" : "brown" } })
Risultato:
{ "_id" : 6, "name" : "Fetch", "type" : "Dog", "specs" : { "height" : 400, "weight" : 15, "color" : "brown" } }
Con la forma annidata, la query deve corrispondere esattamente all'intero documento incorporato. Per esempio, questa query non trova corrispondenze:
db.pets.find({ "specs" : { "height" : 400 } })
Formattare i risultati
Di norma i risultati vengono stampati su una sola riga. Per visualizzarli in un formato piú leggibile, aggiungi il metodo cursor.pretty() a find().
Esempio:
db.pets.find({ "_id": 6 }).pretty()
Risultato:
{ "_id" : 6, "name" : "Fetch", "type" : "Dog", "specs" : { "height" : 400, "weight" : 15, "color" : "brown" } }
Array
Puoi fare riferimento ai dati di un array per indice o per valore.
Supponiamo di inserire:
db.pets.insertOne({ "_id" : 7, "name" : "Jake", "type" : "Dog", "awards" : [ "Top Dog", "Best Dog", "Biggest Dog" ] })
Per trovare tutti i cani con il premio Top Dog potremmo scrivere (il che restituisce il cane qui sopra):
db.pets.find({ "awards": "Top Dog" }).pretty()
Risultato:
{ "_id" : 7, "name" : "Jake", "type" : "Dog", "awards" : [ "Top Dog", "Best Dog", "Biggest Dog" ] }
Puoi anche specificare l'indice dell'elemento:
db.pets.find({ "awards.0": "Top Dog" }).pretty()
Questo richiede che il valore si trovi all'indice indicato, quindi la query seguente non restituisce lo stesso cane.
db.pets.find({ "awards.1": "Top Dog" }).pretty()
Gli array sono a base zero: l'indice 0 è il primo elemento, 1 il secondo e cosí via.
Projection
Per impostazione predefinita find() restituisce tutti i campi. Le projection permettono di ridurre i campi restituiti. Ricorda la sintassi:
db.collection.find(query, projection)
Dove query fornisce il filtro e projection è una specifica opzionale dei campi da restituire. Includi un campo con un 1 oppure escludilo con uno 0.
Supponiamo che la nostra collection ora contenga:
{ "_id" : 1, "name" : "Wag", "type" : "Dog", "weight" : 20 } { "_id" : 2, "name" : "Bark", "type" : "Dog", "weight" : 10 } { "_id" : 3, "name" : "Meow", "type" : "Cat", "weight" : 7 } { "_id" : 4, "name" : "Scratch", "type" : "Cat", "weight" : 8 } { "_id" : 5, "name" : "Bruce", "type" : "Bat", "weight" : 3 } { "_id" : 6, "name" : "Fetch", "type" : "Dog", "specs" : { "height" : 400, "weight" : 15, "color" : "brown" } } { "_id" : 7, "name" : "Jake", "type" : "Dog", "awards" : [ "Top Dog", "Best Dog", "Biggest Dog" ] }
Ecco una projection che include solo alcuni campi:
db.pets.find({}, { name: 1, type: 1 })
Risultato:
{ "_id" : 1, "name" : "Wag", "type" : "Dog" } { "_id" : 2, "name" : "Bark", "type" : "Dog" } { "_id" : 3, "name" : "Meow", "type" : "Cat" } { "_id" : 4, "name" : "Scratch", "type" : "Cat" } { "_id" : 5, "name" : "Bruce", "type" : "Bat" } { "_id" : 6, "name" : "Fetch", "type" : "Dog" } { "_id" : 7, "name" : "Jake", "type" : "Dog" }
Nota che il campo _id viene restituito anche se non lo abbiamo incluso: è un'eccezione, presente per impostazione predefinita. Per ometterlo devi escluderlo esplicitamente.
db.pets.find({}, { _id: 0, name: 1, type: 1 })
Risultato:
{ "name" : "Wag", "type" : "Dog" } { "name" : "Bark", "type" : "Dog" } { "name" : "Meow", "type" : "Cat" } { "name" : "Scratch", "type" : "Cat" } { "name" : "Bruce", "type" : "Bat" } { "name" : "Fetch", "type" : "Dog" } { "name" : "Jake", "type" : "Dog" }
Ecco una projection che specifica solo i campi da escludere:
db.pets.find({}, { _id: 0, weight: 0, specs: 0, awards: 0 })
Risultato:
{ "name" : "Wag", "type" : "Dog" } { "name" : "Bark", "type" : "Dog" } { "name" : "Meow", "type" : "Cat" } { "name" : "Scratch", "type" : "Cat" } { "name" : "Bruce", "type" : "Bat" } { "name" : "Fetch", "type" : "Dog" } { "name" : "Jake", "type" : "Dog" }
Altre possibilitá con le projection
Con le projection c'è molto altro che puoi fare. Per esempio, a partire da MongoDB 4.4 puoi usare espressioni di aggregazione per definire il valore di un campo proiettato.
Esempio:
db.pets.find({}, { "_id": 0, "n": "$name", "t": "$type", "w": "$weight" })
Risultato:
{ "n" : "Wag", "t" : "Dog", "w" : 20 } { "n" : "Bark", "t" : "Dog", "w" : 10 } { "n" : "Meow", "t" : "Cat", "w" : 7 } { "n" : "Scratch", "t" : "Cat", "w" : 8 } { "n" : "Bruce", "t" : "Bat", "w" : 3 } { "n" : "Fetch", "t" : "Dog" } { "n" : "Jake", "t" : "Dog" }
Qui abbiamo rinominato i campi assegnando a ciascuno un nuovo nome come stringa letterale e usando la sintassi $fieldName per输出arne il valore, un po' come si fa con gli alias in SQL.
Approfondimenti
Per maggiori informazioni, consulta la documentazione MongoDB.