Cloud Firestore fornisce potenti funzionalità di query per specificare quali documenti desideri recuperare da una raccolta o da un gruppo di raccolte. Queste query possono essere utilizzate anche con get()
o addSnapshotListener()
, come descritto in Ottenere dati e ottenere aggiornamenti in tempo reale .
Dati di esempio
Per iniziare, scrivi alcuni dati sulle città in modo da poter esaminare diversi modi per rileggerli:
Web modular API
import { collection, doc, setDoc } from "firebase/firestore"; const citiesRef = collection(db, "cities"); await setDoc(doc(citiesRef, "SF"), { name: "San Francisco", state: "CA", country: "USA", capital: false, population: 860000, regions: ["west_coast", "norcal"] }); await setDoc(doc(citiesRef, "LA"), { name: "Los Angeles", state: "CA", country: "USA", capital: false, population: 3900000, regions: ["west_coast", "socal"] }); await setDoc(doc(citiesRef, "DC"), { name: "Washington, D.C.", state: null, country: "USA", capital: true, population: 680000, regions: ["east_coast"] }); await setDoc(doc(citiesRef, "TOK"), { name: "Tokyo", state: null, country: "Japan", capital: true, population: 9000000, regions: ["kanto", "honshu"] }); await setDoc(doc(citiesRef, "BJ"), { name: "Beijing", state: null, country: "China", capital: true, population: 21500000, regions: ["jingjinji", "hebei"] });
Web namespaced API
var citiesRef = db.collection("cities"); citiesRef.doc("SF").set({ name: "San Francisco", state: "CA", country: "USA", capital: false, population: 860000, regions: ["west_coast", "norcal"] }); citiesRef.doc("LA").set({ name: "Los Angeles", state: "CA", country: "USA", capital: false, population: 3900000, regions: ["west_coast", "socal"] }); citiesRef.doc("DC").set({ name: "Washington, D.C.", state: null, country: "USA", capital: true, population: 680000, regions: ["east_coast"] }); citiesRef.doc("TOK").set({ name: "Tokyo", state: null, country: "Japan", capital: true, population: 9000000, regions: ["kanto", "honshu"] }); citiesRef.doc("BJ").set({ name: "Beijing", state: null, country: "China", capital: true, population: 21500000, regions: ["jingjinji", "hebei"] });
Veloce
let citiesRef = db.collection("cities") citiesRef.document("SF").setData([ "name": "San Francisco", "state": "CA", "country": "USA", "capital": false, "population": 860000, "regions": ["west_coast", "norcal"] ]) citiesRef.document("LA").setData([ "name": "Los Angeles", "state": "CA", "country": "USA", "capital": false, "population": 3900000, "regions": ["west_coast", "socal"] ]) citiesRef.document("DC").setData([ "name": "Washington D.C.", "country": "USA", "capital": true, "population": 680000, "regions": ["east_coast"] ]) citiesRef.document("TOK").setData([ "name": "Tokyo", "country": "Japan", "capital": true, "population": 9000000, "regions": ["kanto", "honshu"] ]) citiesRef.document("BJ").setData([ "name": "Beijing", "country": "China", "capital": true, "population": 21500000, "regions": ["jingjinji", "hebei"] ])
Obiettivo-C
FIRCollectionReference *citiesRef = [self.db collectionWithPath:@"cities"]; [[citiesRef documentWithPath:@"SF"] setData:@{ @"name": @"San Francisco", @"state": @"CA", @"country": @"USA", @"capital": @(NO), @"population": @860000, @"regions": @[@"west_coast", @"norcal"] }]; [[citiesRef documentWithPath:@"LA"] setData:@{ @"name": @"Los Angeles", @"state": @"CA", @"country": @"USA", @"capital": @(NO), @"population": @3900000, @"regions": @[@"west_coast", @"socal"] }]; [[citiesRef documentWithPath:@"DC"] setData:@{ @"name": @"Washington D.C.", @"country": @"USA", @"capital": @(YES), @"population": @680000, @"regions": @[@"east_coast"] }]; [[citiesRef documentWithPath:@"TOK"] setData:@{ @"name": @"Tokyo", @"country": @"Japan", @"capital": @(YES), @"population": @9000000, @"regions": @[@"kanto", @"honshu"] }]; [[citiesRef documentWithPath:@"BJ"] setData:@{ @"name": @"Beijing", @"country": @"China", @"capital": @(YES), @"population": @21500000, @"regions": @[@"jingjinji", @"hebei"] }];
Kotlin+KTX
val cities = db.collection("cities") val data1 = hashMapOf( "name" to "San Francisco", "state" to "CA", "country" to "USA", "capital" to false, "population" to 860000, "regions" to listOf("west_coast", "norcal"), ) cities.document("SF").set(data1) val data2 = hashMapOf( "name" to "Los Angeles", "state" to "CA", "country" to "USA", "capital" to false, "population" to 3900000, "regions" to listOf("west_coast", "socal"), ) cities.document("LA").set(data2) val data3 = hashMapOf( "name" to "Washington D.C.", "state" to null, "country" to "USA", "capital" to true, "population" to 680000, "regions" to listOf("east_coast"), ) cities.document("DC").set(data3) val data4 = hashMapOf( "name" to "Tokyo", "state" to null, "country" to "Japan", "capital" to true, "population" to 9000000, "regions" to listOf("kanto", "honshu"), ) cities.document("TOK").set(data4) val data5 = hashMapOf( "name" to "Beijing", "state" to null, "country" to "China", "capital" to true, "population" to 21500000, "regions" to listOf("jingjinji", "hebei"), ) cities.document("BJ").set(data5)
Java
CollectionReference cities = db.collection("cities"); Map<String, Object> data1 = new HashMap<>(); data1.put("name", "San Francisco"); data1.put("state", "CA"); data1.put("country", "USA"); data1.put("capital", false); data1.put("population", 860000); data1.put("regions", Arrays.asList("west_coast", "norcal")); cities.document("SF").set(data1); Map<String, Object> data2 = new HashMap<>(); data2.put("name", "Los Angeles"); data2.put("state", "CA"); data2.put("country", "USA"); data2.put("capital", false); data2.put("population", 3900000); data2.put("regions", Arrays.asList("west_coast", "socal")); cities.document("LA").set(data2); Map<String, Object> data3 = new HashMap<>(); data3.put("name", "Washington D.C."); data3.put("state", null); data3.put("country", "USA"); data3.put("capital", true); data3.put("population", 680000); data3.put("regions", Arrays.asList("east_coast")); cities.document("DC").set(data3); Map<String, Object> data4 = new HashMap<>(); data4.put("name", "Tokyo"); data4.put("state", null); data4.put("country", "Japan"); data4.put("capital", true); data4.put("population", 9000000); data4.put("regions", Arrays.asList("kanto", "honshu")); cities.document("TOK").set(data4); Map<String, Object> data5 = new HashMap<>(); data5.put("name", "Beijing"); data5.put("state", null); data5.put("country", "China"); data5.put("capital", true); data5.put("population", 21500000); data5.put("regions", Arrays.asList("jingjinji", "hebei")); cities.document("BJ").set(data5);
Dart
final cities = db.collection("cities"); final data1 = <String, dynamic>{ "name": "San Francisco", "state": "CA", "country": "USA", "capital": false, "population": 860000, "regions": ["west_coast", "norcal"] }; cities.doc("SF").set(data1); final data2 = <String, dynamic>{ "name": "Los Angeles", "state": "CA", "country": "USA", "capital": false, "population": 3900000, "regions": ["west_coast", "socal"], }; cities.doc("LA").set(data2); final data3 = <String, dynamic>{ "name": "Washington D.C.", "state": null, "country": "USA", "capital": true, "population": 680000, "regions": ["east_coast"] }; cities.doc("DC").set(data3); final data4 = <String, dynamic>{ "name": "Tokyo", "state": null, "country": "Japan", "capital": true, "population": 9000000, "regions": ["kanto", "honshu"] }; cities.doc("TOK").set(data4); final data5 = <String, dynamic>{ "name": "Beijing", "state": null, "country": "China", "capital": true, "population": 21500000, "regions": ["jingjinji", "hebei"], }; cities.doc("BJ").set(data5);
Giava
Pitone
class City: def __init__(self, name, state, country, capital=False, population=0, regions=[]): self.name = name self.state = state self.country = country self.capital = capital self.population = population self.regions = regions @staticmethod def from_dict(source): # ... def to_dict(self): # ... def __repr__(self): return f"City(\ name={self.name}, \ country={self.country}, \ population={self.population}, \ capital={self.capital}, \ regions={self.regions}\ )"
cities_ref = db.collection("cities") cities_ref.document("BJ").set( City("Beijing", None, "China", True, 21500000, ["hebei"]).to_dict() ) cities_ref.document("SF").set( City( "San Francisco", "CA", "USA", False, 860000, ["west_coast", "norcal"] ).to_dict() ) cities_ref.document("LA").set( City( "Los Angeles", "CA", "USA", False, 3900000, ["west_coast", "socal"] ).to_dict() ) cities_ref.document("DC").set( City("Washington D.C.", None, "USA", True, 680000, ["east_coast"]).to_dict() ) cities_ref.document("TOK").set( City("Tokyo", None, "Japan", True, 9000000, ["kanto", "honshu"]).to_dict() )
Python
class City: def __init__(self, name, state, country, capital=False, population=0, regions=[]): self.name = name self.state = state self.country = country self.capital = capital self.population = population self.regions = regions @staticmethod def from_dict(source): # ... def to_dict(self): # ... def __repr__(self): return f"City(\ name={self.name}, \ country={self.country}, \ population={self.population}, \ capital={self.capital}, \ regions={self.regions}\ )"
cities_ref = db.collection("cities") await cities_ref.document("BJ").set( City("Beijing", None, "China", True, 21500000, ["hebei"]).to_dict() ) await cities_ref.document("SF").set( City( "San Francisco", "CA", "USA", False, 860000, ["west_coast", "norcal"] ).to_dict() ) await cities_ref.document("LA").set( City( "Los Angeles", "CA", "USA", False, 3900000, ["west_coast", "socal"] ).to_dict() ) await cities_ref.document("DC").set( City("Washington D.C.", None, "USA", True, 680000, ["east_coast"]).to_dict() ) await cities_ref.document("TOK").set( City("Tokyo", None, "Japan", True, 9000000, ["kanto", "honshu"]).to_dict() )
C++
CollectionReference cities = db->Collection("cities"); cities.Document("SF").Set({ {"name", FieldValue::String("San Francisco")}, {"state", FieldValue::String("CA")}, {"country", FieldValue::String("USA")}, {"capital", FieldValue::Boolean(false)}, {"population", FieldValue::Integer(860000)}, {"regions", FieldValue::Array({FieldValue::String("west_coast"), FieldValue::String("norcal")})}, }); cities.Document("LA").Set({ {"name", FieldValue::String("Los Angeles")}, {"state", FieldValue::String("CA")}, {"country", FieldValue::String("USA")}, {"capital", FieldValue::Boolean(false)}, {"population", FieldValue::Integer(3900000)}, {"regions", FieldValue::Array({FieldValue::String("west_coast"), FieldValue::String("socal")})}, }); cities.Document("DC").Set({ {"name", FieldValue::String("Washington D.C.")}, {"state", FieldValue::Null()}, {"country", FieldValue::String("USA")}, {"capital", FieldValue::Boolean(true)}, {"population", FieldValue::Integer(680000)}, {"regions", FieldValue::Array({FieldValue::String("east_coast")})}, }); cities.Document("TOK").Set({ {"name", FieldValue::String("Tokyo")}, {"state", FieldValue::Null()}, {"country", FieldValue::String("Japan")}, {"capital", FieldValue::Boolean(true)}, {"population", FieldValue::Integer(9000000)}, {"regions", FieldValue::Array({FieldValue::String("kanto"), FieldValue::String("honshu")})}, }); cities.Document("BJ").Set({ {"name", FieldValue::String("Beijing")}, {"state", FieldValue::Null()}, {"country", FieldValue::String("China")}, {"capital", FieldValue::Boolean(true)}, {"population", FieldValue::Integer(21500000)}, {"regions", FieldValue::Array({FieldValue::String("jingjinji"), FieldValue::String("hebei")})}, });
Node.js
Andare
PHP
Unità
CollectionReference citiesRef = db.Collection("cities"); citiesRef.Document("SF").SetAsync(new Dictionary<string, object>(){ { "Name", "San Francisco" }, { "State", "CA" }, { "Country", "USA" }, { "Capital", false }, { "Population", 860000 }, { "Regions", new ArrayList{"west_coast", "norcal"} } }); citiesRef.Document("LA").SetAsync(new Dictionary<string, object>(){ { "Name", "Los Angeles" }, { "State", "CA" }, { "Country", "USA" }, { "Capital", false }, { "Population", 3900000 }, { "Regions", new ArrayList{"west_coast", "socal"} } }); citiesRef.Document("DC").SetAsync(new Dictionary<string, object>(){ { "Name", "Washington D.C." }, { "State", null }, { "Country", "USA" }, { "Capital", true }, { "Population", 680000 }, { "Regions", new ArrayList{"east_coast"} } }); citiesRef.Document("TOK").SetAsync(new Dictionary<string, object>(){ { "Name", "Tokyo" }, { "State", null }, { "Country", "Japan" }, { "Capital", true }, { "Population", 9000000 }, { "Regions", new ArrayList{"kanto", "honshu"} } }); citiesRef.Document("BJ").SetAsync(new Dictionary<string, object>(){ { "Name", "Beijing" }, { "State", null }, { "Country", "China" }, { "Capital", true }, { "Population", 21500000 }, { "Regions", new ArrayList{"jingjinji", "hebei"} } });
C#
Rubino
Domande semplici
La seguente query restituisce tutte le città con CA
dello stato:
Web modular API
// Create a reference to the cities collection import { collection, query, where } from "firebase/firestore"; const citiesRef = collection(db, "cities"); // Create a query against the collection. const q = query(citiesRef, where("state", "==", "CA"));
Web namespaced API
// Create a reference to the cities collection var citiesRef = db.collection("cities"); // Create a query against the collection. var query = citiesRef.where("state", "==", "CA");
Veloce
// Create a reference to the cities collection let citiesRef = db.collection("cities") // Create a query against the collection. let query = citiesRef.whereField("state", isEqualTo: "CA")
Obiettivo-C
// Create a reference to the cities collection FIRCollectionReference *citiesRef = [self.db collectionWithPath:@"cities"]; // Create a query against the collection. FIRQuery *query = [citiesRef queryWhereField:@"state" isEqualTo:@"CA"];
Kotlin+KTX
// Create a reference to the cities collection val citiesRef = db.collection("cities") // Create a query against the collection. val query = citiesRef.whereEqualTo("state", "CA")
Java
// Create a reference to the cities collection CollectionReference citiesRef = db.collection("cities"); // Create a query against the collection. Query query = citiesRef.whereEqualTo("state", "CA");
Dart
// Create a reference to the cities collection final citiesRef = db.collection("cities"); // Create a query against the collection. final query = citiesRef.where("state", isEqualTo: "CA");
Giava
Pitone
Python
C++
CollectionReference cities_ref = db->Collection("cities"); // Create a query against the collection. Query query_ca = cities_ref.WhereEqualTo("state", FieldValue::String("CA"));
Node.js
Andare
PHP
Unità
CollectionReference citiesRef = db.Collection("cities"); Query query = citiesRef.WhereEqualTo("State", "CA"); query.GetSnapshotAsync().ContinueWithOnMainThread((querySnapshotTask) => { foreach (DocumentSnapshot documentSnapshot in querySnapshotTask.Result.Documents) { Debug.Log(String.Format("Document {0} returned by query State=CA", documentSnapshot.Id)); } });
C#
Rubino
La seguente query restituisce tutte le capitali:
Web modular API
import { collection, query, where } from "firebase/firestore"; const citiesRef = collection(db, "cities"); const q = query(citiesRef, where("capital", "==", true));
Web namespaced API
var citiesRef = db.collection("cities"); var query = citiesRef.where("capital", "==", true);
Veloce
let capitalCities = db.collection("cities").whereField("capital", isEqualTo: true)
Obiettivo-C
FIRQuery *capitalCities = [[self.db collectionWithPath:@"cities"] queryWhereField:@"capital" isEqualTo:@YES];
Kotlin+KTX
val capitalCities = db.collection("cities").whereEqualTo("capital", true)
Java
Query capitalCities = db.collection("cities").whereEqualTo("capital", true);
Dart
final capitalcities = db.collection("cities").where("capital", isEqualTo: true);
Giava
Pitone
Python
C++
Query capital_cities = db->Collection("cities").WhereEqualTo( "capital", FieldValue::Boolean(true));
Node.js
Andare
PHP
Unità
CollectionReference citiesRef = db.Collection("cities"); Query query = citiesRef.WhereEqualTo("Capital", true); query.GetSnapshotAsync().ContinueWithOnMainThread((querySnapshotTask) => { foreach (DocumentSnapshot documentSnapshot in querySnapshotTask.Result.Documents) { Debug.Log(String.Format("Document {0} returned by query Capital=true", documentSnapshot.Id)); } });
C#
Rubino
Esegui una query
Dopo aver creato un oggetto query, utilizza la funzione get()
per recuperare i risultati:
Web modular API
import { collection, query, where, getDocs } from "firebase/firestore"; const q = query(collection(db, "cities"), where("capital", "==", true)); const querySnapshot = await getDocs(q); querySnapshot.forEach((doc) => { // doc.data() is never undefined for query doc snapshots console.log(doc.id, " => ", doc.data()); });
Web namespaced API
db.collection("cities").where("capital", "==", true) .get() .then((querySnapshot) => { querySnapshot.forEach((doc) => { // doc.data() is never undefined for query doc snapshots console.log(doc.id, " => ", doc.data()); }); }) .catch((error) => { console.log("Error getting documents: ", error); });
Veloce
do { let querySnapshot = try await db.collection("cities").whereField("capital", isEqualTo: true) .getDocuments() for document in querySnapshot.documents { print("\(document.documentID) => \(document.data())") } } catch { print("Error getting documents: \(error)") }
Obiettivo-C
[[[self.db collectionWithPath:@"cities"] queryWhereField:@"capital" isEqualTo:@(YES)] getDocumentsWithCompletion:^(FIRQuerySnapshot *snapshot, NSError *error) { if (error != nil) { NSLog(@"Error getting documents: %@", error); } else { for (FIRDocumentSnapshot *document in snapshot.documents) { NSLog(@"%@ => %@", document.documentID, document.data); } } }];
Kotlin+KTX
db.collection("cities") .whereEqualTo("capital", true) .get() .addOnSuccessListener { documents -> for (document in documents) { Log.d(TAG, "${document.id} => ${document.data}") } } .addOnFailureListener { exception -> Log.w(TAG, "Error getting documents: ", exception) }
Java
db.collection("cities") .whereEqualTo("capital", true) .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { Log.d(TAG, document.getId() + " => " + document.getData()); } } else { Log.d(TAG, "Error getting documents: ", task.getException()); } } });
Dart
db.collection("cities").where("capital", isEqualTo: true).get().then( (querySnapshot) { print("Successfully completed"); for (var docSnapshot in querySnapshot.docs) { print('${docSnapshot.id} => ${docSnapshot.data()}'); } }, onError: (e) => print("Error completing: $e"), );
Giava
Pitone
Python
C++
db->Collection("cities") .WhereEqualTo("capital", FieldValue::Boolean(true)) .Get() .OnCompletion([](const Future<QuerySnapshot>& future) { if (future.error() == Error::kErrorOk) { for (const DocumentSnapshot& document : future.result()->documents()) { std::cout << document << std::endl; } } else { std::cout << "Error getting documents: " << future.error_message() << std::endl; } });
Node.js
Andare
PHP
PHP
Per ulteriori informazioni sull'installazione e sulla creazione di un client Cloud Firestore, fare riferimento a Librerie client Cloud Firestore .
Unità
Query capitalQuery = db.Collection("cities").WhereEqualTo("Capital", true); capitalQuery.GetSnapshotAsync().ContinueWithOnMainThread(task => { QuerySnapshot capitalQuerySnapshot = task.Result; foreach (DocumentSnapshot documentSnapshot in capitalQuerySnapshot.Documents) { Debug.Log(String.Format("Document data for {0} document:", documentSnapshot.Id)); Dictionary<string, object> city = documentSnapshot.ToDictionary(); foreach (KeyValuePair<string, object> pair in city) { Debug.Log(String.Format("{0}: {1}", pair.Key, pair.Value)); } // Newline to separate entries Debug.Log(""); }; });
C#
Rubino
Vedi Ottieni dati per ulteriori informazioni sul recupero dei risultati della query. Puoi anche aggiungere un ascoltatore a una query per ottenere i risultati correnti e ascoltare gli aggiornamenti futuri.
Operatori di interrogazione
Il metodo where()
accetta tre parametri: un campo su cui filtrare, un operatore di confronto e un valore. Cloud Firestore supporta i seguenti operatori di confronto:
-
<
meno di -
<=
minore o uguale a -
==
uguale a -
>
maggiore di -
>=
maggiore o uguale a -
!=
diverso da -
array-contains
-
array-contains-any
-
in
-
not-in
Per esempio:
Web modular API
const stateQuery = query(citiesRef, where("state", "==", "CA")); const populationQuery = query(citiesRef, where("population", "<", 100000)); const nameQuery = query(citiesRef, where("name", ">=", "San Francisco"));
Web namespaced API
const stateQuery = citiesRef.where("state", "==", "CA"); const populationQuery = citiesRef.where("population", "<", 100000); const nameQuery = citiesRef.where("name", ">=", "San Francisco");
Veloce
let stateQuery = citiesRef.whereField("state", isEqualTo: "CA") let populationQuery = citiesRef.whereField("population", isLessThan: 100000) let nameQuery = citiesRef.whereField("name", isGreaterThanOrEqualTo: "San Francisco")
Obiettivo-C
FIRQuery *stateQuery = [citiesRef queryWhereField:@"state" isEqualTo:@"CA"]; FIRQuery *populationQuery = [citiesRef queryWhereField:@"population" isLessThan:@100000]; FIRQuery *nameQuery = [citiesRef queryWhereField:@"name" isGreaterThanOrEqualTo:@"San Francisco"];
Kotlin+KTX
val stateQuery = citiesRef.whereEqualTo("state", "CA") val populationQuery = citiesRef.whereLessThan("population", 100000) val nameQuery = citiesRef.whereGreaterThanOrEqualTo("name", "San Francisco")
Java
Query stateQuery = citiesRef.whereEqualTo("state", "CA"); Query populationQuery = citiesRef.whereLessThan("population", 100000); Query nameQuery = citiesRef.whereGreaterThanOrEqualTo("name", "San Francisco");
Dart
final citiesRef = db.collection("cities"); final stateQuery = citiesRef.where("state", isEqualTo: "CA"); final populationQuery = citiesRef.where("population", isLessThan: 100000); final nameQuery = citiesRef.where("name", isEqualTo: "San Francisco");
Giava
Pitone
Python
C++
cities_ref.WhereEqualTo("state", FieldValue::String("CA")); cities_ref.WhereLessThan("population", FieldValue::Integer(100000)); cities_ref.WhereGreaterThanOrEqualTo("name", FieldValue::String("San Francisco"));
Node.js
Andare
PHP
Unità
Query stateQuery = citiesRef.WhereEqualTo("State", "CA"); Query populationQuery = citiesRef.WhereGreaterThan("Population", 1000000); Query nameQuery = citiesRef.WhereGreaterThanOrEqualTo("Name", "San Francisco");
C#
Rubino
Non uguale ( !=
)
Utilizzare l'operatore diverso ( !=
) per restituire documenti in cui il campo specificato esiste e non corrisponde al valore di confronto. Per esempio:
Web modular API
const notCapitalQuery = query(citiesRef, where("capital", "!=", false));
Web namespaced API
citiesRef.where("capital", "!=", false);
Veloce
let notEqualQuery = citiesRef.whereField("capital", isNotEqualTo: false)
Obiettivo-C
query = [citiesRef queryWhereField:@"capital" isNotEqualTo:@NO];
Kotlin+KTX
val notCapitalQuery = citiesRef.whereNotEqualTo("capital", false)
Java
Query notCapitalQuery = citiesRef.whereNotEqualTo("capital", false);
Dart
final citiesRef = db.collection("cities"); final notCapitals = citiesRef.where("capital", isNotEqualTo: true);
Giava
Pitone
// Snippet not yet available
C++
cities_ref.WhereNotEqualTo("capital", FieldValue::Boolean(false));
Node.js
Andare
// Snippet not yet available
PHP
Unità
Query query = citiesRef.WhereNotEqualTo("capital", false); Query query = citiesRef.WhereNotEqualTo("capital", false);
C#
// Snippet not yet available
Rubino
Questa query restituisce ogni documento city
in cui esiste il campo capital
con un valore diverso da false
o null
. Ciò include i documenti city
in cui il valore del campo capital
è uguale true
o qualsiasi valore non booleano oltre null
.
Questa query non restituisce documenti city
in cui il campo capital
non esiste. Le query non uguali ( !=
) e not-in
escludono i documenti in cui il campo specificato non esiste .
Un campo esiste quando è impostato su qualsiasi valore, inclusa una stringa vuota ( ""
), null
e NaN
(non un numero). Tieni presente che i valori del campo null
non corrispondono alle clausole !=
, perché x != null
restituisce undefined
.
Limitazioni
Tieni presenti le seguenti limitazioni per le query !=
:
- Solo i documenti in cui esiste il campo specificato possono corrispondere alla query.
- Non è possibile combinare
not-in
e!=
in una query composta. - In una query composta, i confronti tra intervalli (
<
,<=
,>
,>=
) e diversi da (!=
,not-in
) devono essere tutti filtrati sullo stesso campo.
Appartenenza all'array
È possibile utilizzare l'operatore array-contains
per filtrare in base ai valori dell'array. Per esempio:
Web modular API
import { query, where } from "firebase/firestore"; const q = query(citiesRef, where("regions", "array-contains", "west_coast"));
Web namespaced API
citiesRef.where("regions", "array-contains", "west_coast");
Veloce
citiesRef .whereField("regions", arrayContains: "west_coast")
Obiettivo-C
[citiesRef queryWhereField:@"state" arrayContains:@"west_coast"];
Kotlin+KTX
val citiesRef = db.collection("cities") citiesRef.whereArrayContains("regions", "west_coast")
Java
CollectionReference citiesRef = db.collection("cities"); citiesRef.whereArrayContains("regions", "west_coast");
Dart
final citiesRef = db.collection("cities"); final westCoastcities = citiesRef.where("regions", arrayContains: "west_coast");
Giava
Pitone
Python
C++
CollectionReference cities_ref = db->Collection("cities"); cities_ref.WhereArrayContains("region", FieldValue::String("west_coast"));
Node.js
Andare
PHP
Unità
CollectionReference citiesRef = db.Collection("cities"); Query arrayContainsQuery = citiesRef.WhereArrayContains("region", "west_coast");
C#
Rubino
Questa query restituisce ogni documento city
in cui il campo regions
è un array che contiene west_coast
. Se l'array contiene più istanze del valore su cui si esegue la query, il documento viene incluso nei risultati solo una volta.
È possibile utilizzare al massimo una clausola array-contains
per disgiunzione ( or
gruppo). Non è possibile combinare array-contains
con array-contains-any
nella stessa disgiunzione.
in
, not-in
e array-contains-any
Utilizza l'operatore in
per combinare fino a 30 clausole di uguaglianza ( ==
) sullo stesso campo con un OR
logico. Una in
restituisce documenti in cui il campo specificato corrisponde a uno qualsiasi dei valori di confronto. Per esempio:
Web modular API
import { query, where } from "firebase/firestore"; const q = query(citiesRef, where('country', 'in', ['USA', 'Japan']));
Web namespaced API
citiesRef.where('country', 'in', ['USA', 'Japan']);
Veloce
let citiesRef = db.collection("cities") citiesRef.whereField("country", in: ["USA", "Japan"])
Obiettivo-C
FIRCollectionReference *citiesRef = [self.db collectionWithPath:@"cities"]; [citiesRef queryWhereField:@"country" in:@[@"USA", @"Japan"]];
Kotlin+KTX
val citiesRef = db.collection("cities") citiesRef.whereIn("country", listOf("USA", "Japan"))
Java
CollectionReference citiesRef = db.collection("cities"); citiesRef.whereIn("country", Arrays.asList("USA", "Japan"));
Dart
final citiesRef = db.collection("cities"); final cities = citiesRef.where("country", whereIn: ["USA", "Japan"]);
Giava
Pitone
Python
C++
CollectionReference cities_ref = db->Collection("cities"); cities_ref.WhereIn("country", std::vector<FieldValue> { FieldValue::String("USA"), FieldValue::String("Japan") });
Node.js
Andare
PHP
Unità
CollectionReference citiesRef = db.Collection("cities"); ListcountriesList = new List<object>() {"USA", "Japan"}; Query whereInQuery = citiesRef.WhereIn("country", countriesList);
C#
Rubino
Questa query restituisce ogni documento city
in cui il campo country
è impostato su USA
o Japan
. Dai dati di esempio, ciò include i documenti SF
, LA
, DC
e TOK
.
not-in
Utilizza l'operatore not-in
per combinare fino a 10 clausole non uguali ( !=
) nello stesso campo con un AND
logico. Una query not-in
restituisce documenti in cui esiste il campo specificato, non è null
e non corrisponde a nessuno dei valori di confronto. Per esempio:
Web modular API
import { query, where } from "firebase/firestore"; const q = query(citiesRef, where('country', 'not-in', ['USA', 'Japan']));
Web namespaced API
citiesRef.where('country', 'not-in', ['USA', 'Japan']);
Veloce
citiesRef.whereField("country", notIn: ["USA", "Japan"])
Obiettivo-C
[citiesRef queryWhereField:@"country" notIn:@[@"USA", @"Japan"]];
Kotlin+KTX
citiesRef.whereNotIn("country", listOf("USA", "Japan"))
Java
citiesRef.whereNotIn("country", Arrays.asList("USA", "Japan"));
Dart
final citiesRef = db.collection("cities"); final cities = citiesRef.where("country", whereNotIn: ["USA", "Japan"]);
Giava
Pitone
// Snippet not yet available
C++
cities_ref.WhereNotIn("country", std::vector<FieldValue> { FieldValue::String("USA"), FieldValue::String("Japan") });
Node.js
Andare
// Snippet not yet available
PHP
Unità
Query query = citiesRef.WhereNotIn(new FieldPath("country"), new List<string>{"USA", "Japan"}); Query query = citiesRef.WhereNotIn("country", new List<object>(){"USA", "Japan"});
C#
// Snippet not yet available
Rubino
Questa query restituisce ogni documento city
in cui esiste il campo country
e non è impostato su USA
, Japan
o null
. Dai dati di esempio, ciò include i documenti London
e Hong Kong
.
Le query not-in
escludono i documenti in cui il campo specificato non esiste. Un campo esiste quando è impostato su qualsiasi valore, inclusa una stringa vuota ( ""
), null
e NaN
(non un numero). Tieni presente che x != null
restituisce undefined
. Una query not-in
con null
come uno dei valori di confronto non corrisponde ad alcun documento.
array-contains-any
Utilizza l'operatore array-contains-any
per combinare fino a 30 array-contains
sullo stesso campo con un OR
logico. Una array-contains-any
restituisce documenti in cui il campo specificato è un array che contiene uno o più valori di confronto:
Web modular API
import { query, where } from "firebase/firestore"; const q = query(citiesRef, where('regions', 'array-contains-any', ['west_coast', 'east_coast']));
Web namespaced API
citiesRef.where('regions', 'array-contains-any', ['west_coast', 'east_coast']);
Veloce
let citiesRef = db.collection("cities") citiesRef.whereField("regions", arrayContainsAny: ["west_coast", "east_coast"])
Obiettivo-C
FIRCollectionReference *citiesRef = [self.db collectionWithPath:@"cities"]; [citiesRef queryWhereField:@"regions" arrayContainsAny:@[@"west_coast", @"east_coast"]];
Kotlin+KTX
val citiesRef = db.collection("cities") citiesRef.whereArrayContainsAny("regions", listOf("west_coast", "east_coast"))
Java
CollectionReference citiesRef = db.collection("cities"); citiesRef.whereArrayContainsAny("regions", Arrays.asList("west_coast", "east_coast"));
Dart
final citiesRef = db.collection("cities"); final cities = citiesRef .where("regions", arrayContainsAny: ["west_coast", "east_coast"]);
Giava
Pitone
Python
C++
CollectionReference cities_ref = db->Collection("cities"); cities_ref.WhereArrayContainsAny("region", std::vector<FieldValue> { FieldValue::String("west_coast"), FieldValue::String("east_coast") });
Node.js
Andare
PHP
Unità
Query query = citiesRef.WhereArrayContainsAny( "regions", new List<object>() { new List<object>(){"west_coast"}, new List<object>(){"east_coast"}});
C#
Rubino
Questa query restituisce ogni documento di città in cui il campo regions
è un array che contiene west_coast
o east_coast
. Dai dati di esempio, ciò include i documenti SF
, LA
e DC
.
I risultati di array-contains-any
vengono deduplicati. Anche se il campo dell'array di un documento corrisponde a più di uno dei valori di confronto, il set di risultati include quel documento solo una volta.
array-contains-any
filtra sempre in base al tipo di dati dell'array. Ad esempio, la query precedente non restituirebbe un documento di città in cui invece di un array, il campo regions
è la stringa west_coast
.
È possibile utilizzare un valore di array come valore di confronto per in
, ma a differenza di array-contains-any
, la clausola corrisponde a una corrispondenza esatta di lunghezza, ordine e valori dell'array. Per esempio:
Web modular API
import { query, where } from "firebase/firestore"; const q = query(citiesRef, where('regions', 'in', [['west_coast'], ['east_coast']]));
Web namespaced API
citiesRef.where('regions', 'in', [['west_coast'], ['east_coast']]);
Veloce
citiesRef.whereField("regions", in: [["west_coast"], ["east_coast"]])
Obiettivo-C
[citiesRef queryWhereField:@"regions" in:@[@[@"west_coast"], @[@"east_coast"]]];
Kotlin+KTX
citiesRef.whereIn("regions", listOf(arrayOf("west_coast"), arrayOf("east_coast")))
Java
citiesRef.whereIn("regions", Arrays.asList(new String[]{"west_coast"}, new String[]{"east_coast"}));
Dart
final citiesRef = db.collection("cities"); final cities = citiesRef.where("regions", whereIn: [ ["west_coast"], ["east_coast"] ]);
Giava
Pitone
Python
C++
cities_ref.WhereIn("region", std::vector<FieldValue> { FieldValue::String("west_coast"), FieldValue::String("east_coast") });
Node.js
Andare
PHP
Unità
Query query = citiesRef.WhereIn(new FieldPath("regions"), new List<string>{"west_coast", "east_coast"});
C#
Rubino
Questa query restituisce ogni documento di città in cui il campo regions
è un array che contiene esattamente un elemento di west_coast
o east_coast
. Dai dati di esempio, solo il documento DC
si qualifica con il campo delle regions
di ["east_coast"]
. Il documento SF
, tuttavia, non corrisponde perché il campo delle regions
è ["west_coast", "norcal"]
.
Limitazioni
Tieni presenti le seguenti limitazioni per in
, not-in
e array-contains-any
:
- Cloud Firestore fornisce supporto per query
OR
logiche tramite gli operatorior
,in
earray-contains-any
. Queste query sono limitate a 30 disgiunzioni basate sulla forma normale disgiuntiva della query . - È possibile utilizzare al massimo una clausola
array-contains
per disgiunzione (or
gruppo). Non è possibile combinarearray-contains
conarray-contains-any
nella stessa disgiunzione. - Non è possibile combinare
not-in
con not equals!=
. -
not-in
supporta fino a 10 valori di confronto.
Query composte ( AND
).
È possibile combinare i vincoli con un AND
logico concatenando più operatori di uguaglianza ( ==
o array-contains
). Tuttavia, è necessario creare un indice composito per combinare gli operatori di uguaglianza con gli operatori di disuguaglianza <
, <=
, >
e !=
.
Web modular API
import { query, where } from "firebase/firestore"; const q1 = query(citiesRef, where("state", "==", "CO"), where("name", "==", "Denver")); const q2 = query(citiesRef, where("state", "==", "CA"), where("population", "<", 1000000));
Web namespaced API
const q1 = citiesRef.where("state", "==", "CO").where("name", "==", "Denver"); const q2 = citiesRef.where("state", "==", "CA").where("population", "<", 1000000);
Veloce
citiesRef .whereField("state", isEqualTo: "CO") .whereField("name", isEqualTo: "Denver") citiesRef .whereField("state", isEqualTo: "CA") .whereField("population", isLessThan: 1000000)
Obiettivo-C
[[citiesRef queryWhereField:@"state" isEqualTo:@"CO"] queryWhereField:@"name" isGreaterThanOrEqualTo:@"Denver"]; [[citiesRef queryWhereField:@"state" isEqualTo:@"CA"] queryWhereField:@"population" isLessThan:@1000000];
Kotlin+KTX
citiesRef.whereEqualTo("state", "CO").whereEqualTo("name", "Denver") citiesRef.whereEqualTo("state", "CA").whereLessThan("population", 1000000)
Java
citiesRef.whereEqualTo("state", "CO").whereEqualTo("name", "Denver"); citiesRef.whereEqualTo("state", "CA").whereLessThan("population", 1000000);
Dart
final citiesRef = db.collection("cities"); citiesRef .where("state", isEqualTo: "CO") .where("name", isEqualTo: "Denver"); citiesRef .where("state", isEqualTo: "CA") .where("population", isLessThan: 1000000);
Giava
Pitone
Python
C++
cities_ref.WhereEqualTo("state", FieldValue::String("CO")) .WhereEqualTo("name", FieldValue::String("Denver")); cities_ref.WhereEqualTo("state", FieldValue::String("CA")) .WhereLessThan("population", FieldValue::Integer(1000000));
Node.js
Andare
PHP
Unità
Query chainedQuery = citiesRef .WhereEqualTo("State", "CA") .WhereEqualTo("Name", "San Francisco");
C#
Rubino
È possibile eseguire confronti tra intervalli ( <
, <=
, >
, >=
) o diversi ( !=
) solo su un singolo campo ed è possibile includere al massimo una clausola array-contains
o array-contains-any
in una query composta :
Valido : filtri di intervallo su un solo campo
Web modular API
import { query, where } from "firebase/firestore"; const q1 = query(citiesRef, where("state", ">=", "CA"), where("state", "<=", "IN")); const q2 = query(citiesRef, where("state", "==", "CA"), where("population", ">", 1000000));
Web namespaced API
const q1 = citiesRef.where("state", ">=", "CA").where("state", "<=", "IN"); const q2 = citiesRef.where("state", "==", "CA").where("population", ">", 1000000);
Veloce
citiesRef .whereField("state", isGreaterThanOrEqualTo: "CA") .whereField("state", isLessThanOrEqualTo: "IN") citiesRef .whereField("state", isEqualTo: "CA") .whereField("population", isGreaterThan: 1000000)
Obiettivo-C
[[citiesRef queryWhereField:@"state" isGreaterThanOrEqualTo:@"CA"] queryWhereField:@"state" isLessThanOrEqualTo:@"IN"]; [[citiesRef queryWhereField:@"state" isEqualTo:@"CA"] queryWhereField:@"population" isGreaterThan:@1000000];
Kotlin+KTX
citiesRef.whereGreaterThanOrEqualTo("state", "CA") .whereLessThanOrEqualTo("state", "IN") citiesRef.whereEqualTo("state", "CA") .whereGreaterThan("population", 1000000)
Java
citiesRef.whereGreaterThanOrEqualTo("state", "CA") .whereLessThanOrEqualTo("state", "IN"); citiesRef.whereEqualTo("state", "CA") .whereGreaterThan("population", 1000000);
Dart
final citiesRef = db.collection("cities"); citiesRef .where("state", isGreaterThanOrEqualTo: "CA") .where("state", isLessThanOrEqualTo: "IN"); citiesRef .where("state", isEqualTo: "CA") .where("population", isGreaterThan: 1000000);
Giava
Pitone
Python
C++
cities_ref.WhereGreaterThanOrEqualTo("state", FieldValue::String("CA")) .WhereLessThanOrEqualTo("state", FieldValue::String("IN")); cities_ref.WhereEqualTo("state", FieldValue::String("CA")) .WhereGreaterThan("population", FieldValue::Integer(1000000));
Node.js
Andare
PHP
Unità
Query rangeQuery = citiesRef .WhereGreaterThanOrEqualTo("State", "CA") .WhereLessThanOrEqualTo("State", "IN");
C#
Rubino
Non valido : filtri di intervallo su campi diversi
Web modular API
import { query, where } from "firebase/firestore"; const q = query(citiesRef, where("state", ">=", "CA"), where("population", ">", 100000));
Web namespaced API
citiesRef.where("state", ">=", "CA").where("population", ">", 100000);
Veloce
citiesRef .whereField("state", isGreaterThanOrEqualTo: "CA") .whereField("population", isGreaterThan: 1000000)
Obiettivo-C
[[citiesRef queryWhereField:@"state" isGreaterThanOrEqualTo:@"CA"] queryWhereField:@"population" isGreaterThan:@1000000];
Kotlin+KTX
citiesRef.whereGreaterThanOrEqualTo("state", "CA") .whereGreaterThan("population", 100000)
Java
citiesRef.whereGreaterThanOrEqualTo("state", "CA").whereGreaterThan("population", 100000);
Dart
final citiesRef = db.collection("cities"); citiesRef .where("state", isGreaterThanOrEqualTo: "CA") .where("population", isGreaterThan: 1000000);
Giava
Pitone
Python
C++
// BAD EXAMPLE -- will crash the program: cities_ref.WhereGreaterThanOrEqualTo("state", FieldValue::String("CA")) .WhereGreaterThan("population", FieldValue::Integer(100000));
Node.js
Andare
PHP
Unità
Query invalidRangeQuery = citiesRef .WhereGreaterThanOrEqualTo("State", "CA") .WhereGreaterThan("Population", 1000000);
C#
Rubino
OR
query
È possibile combinare i vincoli con un OR
logico. Per esempio:
Web modular API
const q = query(citiesRef, or(where('capital', '==', true), where('population', '>=', 1000000) ) );
Web namespaced API
Non disponibile.
Veloce
let query = db.collection("cities").whereFilter(Filter.orFilter([ Filter.whereField("capital", isEqualTo: true), Filter.whereField("population", isGreaterThanOrEqualTo: 1000000); ]))
Obiettivo-C
FIRCollectionReference *collection = [self.db collectionWithPath:@"cities"]; FIRQuery *query = [collection queryWhereFilter:[FIRFilter orFilterWithFilters:@[ [FIRFilter filterWhereField:@"capital" isEqualTo:@YES], [FIRFilter filterWhereField:@"population" isGreaterThanOrEqualTo:@1000000] ]]];
Kotlin+KTX
val query = collection.where(Filter.or( Filter.equalTo("capital", true), Filter.greaterThanOrEqualTo("population", 1000000) ))
Java
Query query = collection.where(Filter.or( Filter.equalTo("capital", true), Filter.greaterThanOrEqualTo("population", 1000000) ));
Dart
var query = db.collection("cities") .where( Filter.or( Filter("capital", isEqualTo: true), Filter("population", isGreaterThan: 1000000) ));
Giava
Frammento non disponibile.
Pitone
Python
Frammento non disponibile.
C++
Frammento non disponibile.
Node.js
const bigCities = await citiesRef .where( Filter.or( Filter.where('capital', '==', true), Filter.where('population', '>=', 1000000) ) ) .get();
Andare
PHP
Frammento non disponibile.
Unità
Query query = citiesRef.Where(Filter.Or( Filter.EqualTo("State", "CA"), Filter.GreaterThanOrEqualTo("population", 1000000) )); query.GetSnapshotAsync().ContinueWithOnMainThread((querySnapshotTask) => { foreach (DocumentSnapshot documentSnapshot in querySnapshotTask.Result.Documents) { Debug.Log(String.Format("Document {0} returned by query State=CA or population >= {1}", documentSnapshot.Id, 1000000)); } });
C#
Frammento non disponibile.
Rubino
Frammento non disponibile.
Cloud Firestore utilizza i tuoi indici compositi per servire query OR
. Se i tuoi indici non supportano la query, Cloud Firestore suggerisce indici aggiuntivi per il tuo database .
È possibile combinare query OR
con query composte per filtrare combinazioni di operazioni OR
e AND
. Per esempio:
Web modular API
const q = query(collection(db, "cities"), and( where('state', '==', 'CA'), or( where('capital', '==', true), where('population', '>=', 1000000) ) ));
Web namespaced API
Non disponibile.
Veloce
let query = db.collection("cities").whereFilter(Filter.andFilter([ Filter.whereField("state", isEqualTo: "CA"), Filter.orFilter([ Filter.whereField("capital", isEqualTo: true), Filter.whereField("population", isGreaterThanOrEqualTo: 1000000); ]) ]))
Obiettivo-C
FIRCollectionReference *collection = [self.db collectionWithPath:@"cities"]; FIRQuery *query = [collection queryWhereFilter:[FIRFilter andFilterWithFilters:@[ [FIRFilter filterWhereField:@"state" isEqualTo:@"CA"], [FIRFilter orFilterWithFilters:@[ [FIRFilter filterWhereField:@"capital" isEqualTo:@YES], [FIRFilter filterWhereField:@"population" isGreaterThanOrEqualTo:@1000000] ]] ]]];
Kotlin+KTX
val query = collection.where(Filter.and( Filter.equalTo("state", "CA"), Filter.or( Filter.equalTo("capital", true), Filter.greaterThanOrEqualTo("population", 1000000) ) ))
Java
Query query = collection.where(Filter.and( Filter.equalTo("state", "CA"), Filter.or( Filter.equalTo("capital", true), Filter.greaterThanOrEqualTo("population", 1000000) ) ));
Dart
var query = db.collection("cities") .where( Filter.and( Filter("state", isEqualTo: "CA"), Filter.or( Filter("capital", isEqualTo: true), Filter("population", isGreaterThan: 1000000) )));
Giava
Frammento non disponibile.
Pitone
Frammento non disponibile.
Python
Frammento non disponibile.
C++
Frammento non disponibile.
Node.js
const bigCitiesInCalifornia = await citiesRef .where('state', '==', 'CA') .where( Filter.or( Filter.where('capital', '==', true), Filter.where('population', '>=', 1000000) ) ) .get();
Andare
Frammento non disponibile.
PHP
Frammento non disponibile.
Unità
Query query = citiesRef.Where(Filter.And( Filter.EqualTo("state", "CA"), Filter.Or( Filter.EqualTo("capital", true), Filter.GreaterThanOrEqualTo("population", 1000000) ) ));
C#
Frammento non disponibile.
Rubino
Frammento non disponibile.
Limitazioni
Tieni presenti le seguenti limitazioni per or
query:
- Cloud Firestore limita una query a un massimo di 30 disgiunzioni in base alla forma normale disgiuntiva della query . È più probabile che tu raggiunga questo limite quando esegui un
AND
di più gruppiOR
. - Non è possibile combinare
not-in
conin
,array-contains-any
oor
nella stessa query.
Per una descrizione completa delle limitazioni, consulta Limitazioni delle query .
Query sul gruppo di raccolta
Un gruppo di raccolte è costituito da tutte le raccolte con lo stesso ID. Per impostazione predefinita, le query recuperano i risultati da una singola raccolta nel database. Utilizzare una query del gruppo di raccolte per recuperare documenti da un gruppo di raccolte anziché da una singola raccolta.
Ad esempio, puoi creare un gruppo di raccolte landmarks
aggiungendo una sottoraccolta di punti di riferimento a ciascuna città:
Web modular API
import { collection, addDoc } from "firebase/firestore"; const citiesRef = collection(db, 'cities'); await Promise.all([ addDoc(collection(citiesRef, 'SF', 'landmarks'), { name: 'Golden Gate Bridge', type: 'bridge' }), addDoc(collection(citiesRef, 'SF', 'landmarks'), { name: 'Legion of Honor', type: 'museum' }), addDoc(collection(citiesRef, 'LA', 'landmarks'), { name: 'Griffith Park', type: 'park' }), addDoc(collection(citiesRef, 'LA', 'landmarks'), { name: 'The Getty', type: 'museum' }), addDoc(collection(citiesRef, 'DC', 'landmarks'), { name: 'Lincoln Memorial', type: 'memorial' }), addDoc(collection(citiesRef, 'DC', 'landmarks'), { name: 'National Air and Space Museum', type: 'museum' }), addDoc(collection(citiesRef, 'TOK', 'landmarks'), { name: 'Ueno Park', type: 'park' }), addDoc(collection(citiesRef, 'TOK', 'landmarks'), { name: 'National Museum of Nature and Science', type: 'museum' }), addDoc(collection(citiesRef, 'BJ', 'landmarks'), { name: 'Jingshan Park', type: 'park' }), addDoc(collection(citiesRef, 'BJ', 'landmarks'), { name: 'Beijing Ancient Observatory', type: 'museum' }) ]);
Web namespaced API
var citiesRef = db.collection('cities'); var landmarks = Promise.all([ citiesRef.doc('SF').collection('landmarks').doc().set({ name: 'Golden Gate Bridge', type: 'bridge' }), citiesRef.doc('SF').collection('landmarks').doc().set({ name: 'Legion of Honor', type: 'museum' }), citiesRef.doc('LA').collection('landmarks').doc().set({ name: 'Griffith Park', type: 'park' }), citiesRef.doc('LA').collection('landmarks').doc().set({ name: 'The Getty', type: 'museum' }), citiesRef.doc('DC').collection('landmarks').doc().set({ name: 'Lincoln Memorial', type: 'memorial' }), citiesRef.doc('DC').collection('landmarks').doc().set({ name: 'National Air and Space Museum', type: 'museum' }), citiesRef.doc('TOK').collection('landmarks').doc().set({ name: 'Ueno Park', type: 'park' }), citiesRef.doc('TOK').collection('landmarks').doc().set({ name: 'National Museum of Nature and Science', type: 'museum' }), citiesRef.doc('BJ').collection('landmarks').doc().set({ name: 'Jingshan Park', type: 'park' }), citiesRef.doc('BJ').collection('landmarks').doc().set({ name: 'Beijing Ancient Observatory', type: 'museum' }) ]);
Veloce
let citiesRef = db.collection("cities") var data = ["name": "Golden Gate Bridge", "type": "bridge"] citiesRef.document("SF").collection("landmarks").addDocument(data: data) data = ["name": "Legion of Honor", "type": "museum"] citiesRef.document("SF").collection("landmarks").addDocument(data: data) data = ["name": "Griffith Park", "type": "park"] citiesRef.document("LA").collection("landmarks").addDocument(data: data) data = ["name": "The Getty", "type": "museum"] citiesRef.document("LA").collection("landmarks").addDocument(data: data) data = ["name": "Lincoln Memorial", "type": "memorial"] citiesRef.document("DC").collection("landmarks").addDocument(data: data) data = ["name": "National Air and Space Museum", "type": "museum"] citiesRef.document("DC").collection("landmarks").addDocument(data: data) data = ["name": "Ueno Park", "type": "park"] citiesRef.document("TOK").collection("landmarks").addDocument(data: data) data = ["name": "National Museum of Nature and Science", "type": "museum"] citiesRef.document("TOK").collection("landmarks").addDocument(data: data) data = ["name": "Jingshan Park", "type": "park"] citiesRef.document("BJ").collection("landmarks").addDocument(data: data) data = ["name": "Beijing Ancient Observatory", "type": "museum"] citiesRef.document("BJ").collection("landmarks").addDocument(data: data)
Obiettivo-C
FIRCollectionReference *citiesRef = [self.db collectionWithPath:@"cities"]; NSDictionary *data = @{@"name": @"Golden Gate Bridge", @"type": @"bridge"}; [[[citiesRef documentWithPath:@"SF"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; data = @{@"name": @"Legion of Honor", @"type": @"museum"}; [[[citiesRef documentWithPath:@"SF"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; data = @{@"name": @"Griffith Park", @"type": @"park"}; [[[citiesRef documentWithPath:@"LA"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; data = @{@"name": @"The Getty", @"type": @"museum"}; [[[citiesRef documentWithPath:@"LA"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; data = @{@"name": @"Lincoln Memorial", @"type": @"memorial"}; [[[citiesRef documentWithPath:@"DC"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; data = @{@"name": @"National Air and Space Museum", @"type": @"museum"}; [[[citiesRef documentWithPath:@"DC"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; data = @{@"name": @"Ueno Park", @"type": @"park"}; [[[citiesRef documentWithPath:@"TOK"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; data = @{@"name": @"National Museum of Nature and Science", @"type": @"museum"}; [[[citiesRef documentWithPath:@"TOK"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; data = @{@"name": @"Jingshan Park", @"type": @"park"}; [[[citiesRef documentWithPath:@"BJ"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; data = @{@"name": @"Beijing Ancient Observatory", @"type": @"museum"}; [[[citiesRef documentWithPath:@"BJ"] collectionWithPath:@"landmarks"] addDocumentWithData:data];
Kotlin+KTX
val citiesRef = db.collection("cities") val ggbData = mapOf( "name" to "Golden Gate Bridge", "type" to "bridge", ) citiesRef.document("SF").collection("landmarks").add(ggbData) val lohData = mapOf( "name" to "Legion of Honor", "type" to "museum", ) citiesRef.document("SF").collection("landmarks").add(lohData) val gpData = mapOf( "name" to "Griffth Park", "type" to "park", ) citiesRef.document("LA").collection("landmarks").add(gpData) val tgData = mapOf( "name" to "The Getty", "type" to "museum", ) citiesRef.document("LA").collection("landmarks").add(tgData) val lmData = mapOf( "name" to "Lincoln Memorial", "type" to "memorial", ) citiesRef.document("DC").collection("landmarks").add(lmData) val nasaData = mapOf( "name" to "National Air and Space Museum", "type" to "museum", ) citiesRef.document("DC").collection("landmarks").add(nasaData) val upData = mapOf( "name" to "Ueno Park", "type" to "park", ) citiesRef.document("TOK").collection("landmarks").add(upData) val nmData = mapOf( "name" to "National Musuem of Nature and Science", "type" to "museum", ) citiesRef.document("TOK").collection("landmarks").add(nmData) val jpData = mapOf( "name" to "Jingshan Park", "type" to "park", ) citiesRef.document("BJ").collection("landmarks").add(jpData) val baoData = mapOf( "name" to "Beijing Ancient Observatory", "type" to "musuem", ) citiesRef.document("BJ").collection("landmarks").add(baoData)
Java
CollectionReference citiesRef = db.collection("cities"); Map<String, Object> ggbData = new HashMap<>(); ggbData.put("name", "Golden Gate Bridge"); ggbData.put("type", "bridge"); citiesRef.document("SF").collection("landmarks").add(ggbData); Map<String, Object> lohData = new HashMap<>(); lohData.put("name", "Legion of Honor"); lohData.put("type", "museum"); citiesRef.document("SF").collection("landmarks").add(lohData); Map<String, Object> gpData = new HashMap<>(); gpData.put("name", "Griffith Park"); gpData.put("type", "park"); citiesRef.document("LA").collection("landmarks").add(gpData); Map<String, Object> tgData = new HashMap<>(); tgData.put("name", "The Getty"); tgData.put("type", "museum"); citiesRef.document("LA").collection("landmarks").add(tgData); Map<String, Object> lmData = new HashMap<>(); lmData.put("name", "Lincoln Memorial"); lmData.put("type", "memorial"); citiesRef.document("DC").collection("landmarks").add(lmData); Map<String, Object> nasaData = new HashMap<>(); nasaData.put("name", "National Air and Space Museum"); nasaData.put("type", "museum"); citiesRef.document("DC").collection("landmarks").add(nasaData); Map<String, Object> upData = new HashMap<>(); upData.put("name", "Ueno Park"); upData.put("type", "park"); citiesRef.document("TOK").collection("landmarks").add(upData); Map<String, Object> nmData = new HashMap<>(); nmData.put("name", "National Museum of Nature and Science"); nmData.put("type", "museum"); citiesRef.document("TOK").collection("landmarks").add(nmData); Map<String, Object> jpData = new HashMap<>(); jpData.put("name", "Jingshan Park"); jpData.put("type", "park"); citiesRef.document("BJ").collection("landmarks").add(jpData); Map<String, Object> baoData = new HashMap<>(); baoData.put("name", "Beijing Ancient Observatory"); baoData.put("type", "museum"); citiesRef.document("BJ").collection("landmarks").add(baoData);
Dart
final citiesRef = db.collection("cities"); final ggbData = {"name": "Golden Gate Bridge", "type": "bridge"}; citiesRef.doc("SF").collection("landmarks").add(ggbData); final lohData = {"name": "Legion of Honor", "type": "museum"}; citiesRef.doc("SF").collection("landmarks").add(lohData); final gpData = {"name": "Griffth Park", "type": "park"}; citiesRef.doc("LA").collection("landmarks").add(gpData); final tgData = {"name": "The Getty", "type": "museum"}; citiesRef.doc("LA").collection("landmarks").add(tgData); final lmData = {"name": "Lincoln Memorial", "type": "memorial"}; citiesRef.doc("DC").collection("landmarks").add(lmData); final nasaData = { "name": "National Air and Space Museum", "type": "museum" }; citiesRef.doc("DC").collection("landmarks").add(nasaData); final upData = {"name": "Ueno Park", "type": "park"}; citiesRef.doc("TOK").collection("landmarks").add(upData); final nmData = { "name": "National Musuem of Nature and Science", "type": "museum" }; citiesRef.doc("TOK").collection("landmarks").add(nmData); final jpData = {"name": "Jingshan Park", "type": "park"}; citiesRef.doc("BJ").collection("landmarks").add(jpData); final baoData = {"name": "Beijing Ancient Observatory", "type": "musuem"}; citiesRef.doc("BJ").collection("landmarks").add(baoData);
Giava
Pitone
Python
C++
// Get a new write batch WriteBatch batch = db->batch(); DocumentReference sf_ref = db->Collection("cities").Document("SF"); batch.Set(sf_ref,{{"name", FieldValue::String("Golden Gate Bridge")}, {"type", FieldValue::String("bridge")}}); batch.Set(sf_ref,{{"name", FieldValue::String("Legion of Honor")}, {"type", FieldValue::String("museum")}}); DocumentReference la_ref = db->Collection("cities").Document("LA"); batch.Set(la_ref,{{"name", FieldValue::String("Griffith Park")}, {"type", FieldValue::String("park")}}); batch.Set(la_ref,{{"name", FieldValue::String("The Getty")}, {"type", FieldValue::String("museum")}}); DocumentReference dc_ref = db->Collection("cities").Document("DC"); batch.Set(dc_ref,{{"name", FieldValue::String("Lincoln Memorial")}, {"type", FieldValue::String("memorial")}}); batch.Set(dc_ref,{{"name", FieldValue::String("National Air and Space Museum")}, {"type", FieldValue::String("museum")}}); DocumentReference tok_ref = db->Collection("cities").Document("TOK"); batch.Set(tok_ref,{{"name", FieldValue::String("Ueno Park")}, {"type", FieldValue::String("park")}}); batch.Set(tok_ref,{{"name", FieldValue::String("National Museum of Nature and Science")}, {"type", FieldValue::String("museum")}}); DocumentReference bj_ref = db->Collection("cities").Document("BJ"); batch.Set(bj_ref,{{"name", FieldValue::String("Jingshan Park")}, {"type", FieldValue::String("park")}}); batch.Set(bj_ref,{{"name", FieldValue::String("Beijing Ancient Observatory")}, {"type", FieldValue::String("museum")}}); // Commit the batch batch.Commit().OnCompletion([](const Future<void>& future) { if (future.error() == Error::kErrorOk) { std::cout << "Write batch success!" << std::endl; } else { std::cout << "Write batch failure: " << future.error_message() << std::endl; } });
Node.js
Andare
PHP
Unità
List<Task<DocumentReference>> futures = new List<Task<DocumentReference>>(){ citiesRef .Document("SF") .Collection("landmarks") .AddAsync( new Dictionary<string, object>() { {"name", "Golden Gate Bridge"}, {"type", "bridge"}, } ), citiesRef .Document("SF") .Collection("landmarks") .AddAsync( new Dictionary<string, object>() { {"name", "Legion of Honor"}, {"type", "museum"}, } ), citiesRef .Document("LA") .Collection("landmarks") .AddAsync( new Dictionary<string, object>() { {"name", "Griffith Park"}, {"type", "park"}, } ), citiesRef .Document("LA") .Collection("landmarks") .AddAsync( new Dictionary<string, object>() { {"name", "The Getty"}, {"type", "museum"}, } ), citiesRef .Document("DC") .Collection("landmarks") .AddAsync( new Dictionary<string, object>() { {"name", "Lincoln Memorial"}, {"type", "memorial"}, } ), citiesRef .Document("DC") .Collection("landmarks") .AddAsync( new Dictionary<string, object>() { {"name", "National Air and Space Museum"}, {"type", "museum"}, } ), citiesRef .Document("TOK") .Collection("landmarks") .AddAsync( new Dictionary<string, object>() { {"name", "Ueno Park"}, {"type", "park"}, } ), citiesRef .Document("TOK") .Collection("landmarks") .AddAsync( new Dictionary<string, object>() { {"name", "National Museum of Nature and Science"}, {"type", "museum"}, } ), citiesRef .Document("BJ") .Collection("landmarks") .AddAsync( new Dictionary<string, object>() { {"name", "Jingshan Park"}, {"type", "park"}, } ), citiesRef .Document("BJ") .Collection("landmarks") .AddAsync( new Dictionary<string, object>() { {"name", "Beijing Ancient Observatory"}, {"type", "museum"}, } )}; DocumentReference[] landmarks = Task.WhenAll(futures).Result;
C#
Rubino
Possiamo utilizzare la query semplice e composta descritta in precedenza per interrogare la sottoraccolta landmarks
di una singola città, ma potresti anche voler recuperare i risultati dalla sottoraccolta landmarks
di ogni città contemporaneamente.
Il gruppo di raccolta landmarks
è costituito da tutte le raccolte con l'ID landmarks
ed è possibile interrogarlo utilizzando una query del gruppo di raccolta. Ad esempio, questa query del gruppo di raccolte recupera tutti i punti di riferimento museum
in tutte le città:
Web modular API
import { collectionGroup, query, where, getDocs } from "firebase/firestore"; const museums = query(collectionGroup(db, 'landmarks'), where('type', '==', 'museum')); const querySnapshot = await getDocs(museums); querySnapshot.forEach((doc) => { console.log(doc.id, ' => ', doc.data()); });
Web namespaced API
var museums = db.collectionGroup('landmarks').where('type', '==', 'museum'); museums.get().then((querySnapshot) => { querySnapshot.forEach((doc) => { console.log(doc.id, ' => ', doc.data()); }); });
Veloce
db.collectionGroup("landmarks").whereField("type", isEqualTo: "museum").getDocuments { (snapshot, error) in // ... }
Obiettivo-C
[[[self.db collectionGroupWithID:@"landmarks"] queryWhereField:@"type" isEqualTo:@"museum"] getDocumentsWithCompletion:^(FIRQuerySnapshot *snapshot, NSError *error) { // ... }];
Kotlin+KTX
db.collectionGroup("landmarks").whereEqualTo("type", "museum").get() .addOnSuccessListener { queryDocumentSnapshots -> // ... }
Java
db.collectionGroup("landmarks").whereEqualTo("type", "museum").get() .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() { @Override public void onSuccess(QuerySnapshot queryDocumentSnapshots) { // ... } });
Dart
db .collectionGroup("landmarks") .where("type", isEqualTo: "museum") .get() .then( (res) => print("Successfully completed"), onError: (e) => print("Error completing: $e"), );
Giava
Pitone
Python
C++
db->CollectionGroup("landmarks") .WhereEqualTo("type", FieldValue::String("museum")).Get() .OnCompletion([](const firebase::Future<QuerySnapshot>& future) { if (future.error() == Error::kErrorOk) { for (const DocumentSnapshot& document : future.result()->documents()) { std::cout << document << std::endl; } } else { std::cout << "Error getting documents: " << future.error_message() << std::endl; } });
Node.js
Andare
PHP
Unità
Query museums = db.CollectionGroup("landmarks").WhereEqualTo("type", "museum"); museums.GetSnapshotAsync().ContinueWithOnMainThread((querySnapshotTask) => { foreach (DocumentSnapshot documentSnapshot in querySnapshotTask.Result.Documents) { Debug.Log(String.Format("Document {0} returned by query State=CA", documentSnapshot.Id)); } });
C#
Rubino
Prima di utilizzare una query del gruppo di raccolta, è necessario creare un indice che supporti la query del gruppo di raccolta. Puoi creare un indice tramite un messaggio di errore, la console o la CLI di Firebase .
Per gli SDK Web e mobili, devi anche creare regole che consentano le query del gruppo di raccolta .
Limitazioni delle query
L'elenco seguente riepiloga le limitazioni delle query di Cloud Firestore:
- Cloud Firestore fornisce supporto per query
OR
logiche tramite gli operatorior
,in
earray-contains-any
. Queste query sono limitate a 30 disgiunzioni basate sulla forma normale disgiuntiva della query . - In una query composta, i confronti tra intervalli (
<
,<=
,>
,>=
) e diversi da (!=
,not-in
) devono essere tutti filtrati sullo stesso campo. - È possibile utilizzare al massimo una clausola
array-contains
per disgiunzione (or
gruppo). Non è possibile combinarearray-contains
conarray-contains-any
nella stessa disgiunzione. - Non è possibile combinare
not-in
conin
,array-contains-any
oor
nella stessa query. - È consentito solo un singolo
not-in
o!=
` per query. -
not-in
supporta fino a 10 valori di confronto. - La somma di filtri, ordinamenti e percorso del documento principale (1 per una sottoraccolta, 0 per una raccolta radice) in una query non può superare 100. Questo viene calcolato in base alla forma normale disgiuntiva della query .
- Una query con un filtro di disuguaglianza su un campo implica l'ordinamento in base a quel campo e filtri per l'esistenza di quel campo .
Limiti sulle query OR
Per evitare che una query diventi troppo costosa dal punto di vista computazionale, Cloud Firestore limita il numero di clausole AND
e OR
che puoi combinare. Per applicare questo limite, Cloud Firestore converte le query che eseguono operazioni OR
logiche ( or
, in
e array-contains-any
) nella forma normale disgiuntiva (nota anche come OR
di AND
). Cloud Firestore limita una query a un massimo di 30 disgiunzioni in forma normale disgiuntiva.
Forma normale disgiuntiva
Cloud Firestore converte le query nella forma normale disgiuntiva applicando due regole:
Appiattire
Date le condizioni
A
,B
eC
:A and (B and C) => A and B and C
Date le condizioni
A
,B
,C
eD
:-
A and (B or C) => (A and B) or (A and C)
-
(A or B) and (C or D) => (A and C) or (A and D) or (B and C) or (B and D)
-
Quando applichi queste regole alle query in
e array-contains-any
, ricorda che questi operatori sono abbreviazioni di OR
. Ad esempio, a in [1,2]
è una scorciatoia per a = 1 OR a = 2
.
I seguenti esempi mostrano il numero di disgiunzioni per diverse query:
Domanda | Numero di disgiunzioni |
---|---|
query(collectionRef, where("a", "==", 1)) | 1 |
query(collectionRef, or( where("a", "==", 1), where("b", "==", 2) )) | 2 |
query(collectionRef, or( and( where("a", "==", 1), where("c", "==", 3) ), and( where("a", "==", 1), where("d", "==", 4) ), and( where("b", "==", 2), where("c", "==", 3) ), and( where("b", "==", 2), where("d", "==", 4) ) ) ) | 4 |
query(collectionRef, and( or( where("a", "==", 1), where("b", "==", 2) ), or( where("c", "==", 3), where("d", "==", 4) ) ) ) | 4 La forma normale disgiuntiva di questa query è uguale alla query precedente. |
query(collectionRef, where("a", "in", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) ) | 10 |
query(collectionRef, and( where("a", "in", [1, 2, 3, 4, 5]), where("b", "in", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) ) ) | 50 Questa query restituisce un errore perché supera il limite di 30 disgiunzioni. |
query(collectionRef, or( where("a", "in", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), where("b", "in", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) ) ) | 20 |
query(collectionRef, and( where("a", "in", [1, 2, 3, 4, 5]), or( where("b", "==", 2), where("c", "==", 3) ) ) ) | 10 |
orderBy
ed esistenza
Quando ordini una query in base a un determinato campo, la query può restituire solo i documenti in cui esiste il campo ordinato per.
Ad esempio, la query seguente non restituirebbe alcun documento in cui il campo population
non è impostato, anche se soddisfano altrimenti i filtri della query.
Giava
db.collection("cities").whereEqualTo("country", “USA”).orderBy(“population”);
Un effetto correlato si applica alle disuguaglianze. Una query con un filtro di disuguaglianza su un campo implica anche l'ordinamento in base a quel campo. La seguente query non restituisce documenti senza un campo population
anche se country = USA
in quel documento. Come soluzione alternativa, è possibile eseguire query separate per ciascun ordinamento oppure assegnare un valore per tutti i campi in base all'ordine.
Giava
db.collection(“cities”).where(or(“country”, USA”), greaterThan(“population”, 250000));
La query precedente include un ordine implicito sulla disuguaglianza ed è equivalente alla seguente:
Giava
db.collection(“cities”).where(or(“country”, USA”), greaterThan(“population”, 250000)).orderBy(“population”);
Qual è il prossimo
- Scopri come ordinare e limitare i dati nei risultati delle query .
- Salva le letture quando vuoi semplicemente contare i risultati .