Cloud Firestore, क्वेरी की बेहतर सुविधा देता है. इससे यह तय किया जा सकता है कि आपको किसी कलेक्शन या कलेक्शन ग्रुप से कौनसे दस्तावेज़ वापस लाने हैं. इन क्वेरी का इस्तेमाल get()
या addSnapshotListener()
के साथ भी किया जा सकता है. इस बारे में डेटा पाना और रीयल टाइम अपडेट पाना में बताया गया है.
डेटा का उदाहरण
शुरू करने के लिए, शहरों के बारे में कुछ डेटा लिखें, ताकि हम इसे पढ़ने के अलग-अलग तरीकों को देख सकें:
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"] });
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"] });
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"] ])
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"] }];
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)
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);
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);
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() )
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() )
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")})}, });
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"} } });
आसान क्वेरी
यहां दी गई क्वेरी से, CA
राज्य वाले सभी शहरों की जानकारी मिलती है:
// 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"));
// Create a reference to the cities collection var citiesRef = db.collection("cities"); // Create a query against the collection. var query = citiesRef.where("state", "==", "CA");
// 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")
// 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"];
// Create a reference to the cities collection val citiesRef = db.collection("cities") // Create a query against the collection. val query = citiesRef.whereEqualTo("state", "CA")
// Create a reference to the cities collection CollectionReference citiesRef = db.collection("cities"); // Create a query against the collection. Query query = citiesRef.whereEqualTo("state", "CA");
// 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");
CollectionReference cities_ref = db->Collection("cities"); // Create a query against the collection. Query query_ca = cities_ref.WhereEqualTo("state", FieldValue::String("CA"));
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)); } });
इस क्वेरी से सभी राजधानियों की जानकारी मिलती है:
import { collection, query, where } from "firebase/firestore"; const citiesRef = collection(db, "cities"); const q = query(citiesRef, where("capital", "==", true));
var citiesRef = db.collection("cities"); var query = citiesRef.where("capital", "==", true);
let capitalCities = db.collection("cities").whereField("capital", isEqualTo: true)
FIRQuery *capitalCities = [[self.db collectionWithPath:@"cities"] queryWhereField:@"capital" isEqualTo:@YES];
val capitalCities = db.collection("cities").whereEqualTo("capital", true)
Query capitalCities = db.collection("cities").whereEqualTo("capital", true);
final capitalcities = db.collection("cities").where("capital", isEqualTo: true);
Query capital_cities = db->Collection("cities").WhereEqualTo( "capital", FieldValue::Boolean(true));
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)); } });
क्वेरी चलाना
क्वेरी ऑब्जेक्ट बनाने के बाद, नतीजे पाने के लिए get()
फ़ंक्शन का इस्तेमाल करें:
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()); });
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); });
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)") }
[[[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); } } }];
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) }
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()); } } });
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"), );
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; } });
PHP
Cloud Firestore क्लाइंट को इंस्टॉल करने और बनाने के बारे में ज़्यादा जानने के लिए, Cloud Firestore क्लाइंट लाइब्रेरी देखें.
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(""); }; });
क्वेरी के नतीजे पाने के बारे में ज़्यादा जानकारी के लिए, डेटा पाना देखें. मौजूदा नतीजे पाने और आने वाले समय में होने वाले अपडेट के बारे में जानने के लिए, किसी क्वेरी में लिसनर जोड़ा जा सकता है.
क्वेरी ऑपरेटर
where()
वाला तरीका तीन पैरामीटर लेता है: फ़िल्टर करने के लिए कोई फ़ील्ड, तुलना करने वाला ऑपरेटर, और कोई वैल्यू. Cloud Firestore में तुलना करने के लिए ये ऑपरेटर इस्तेमाल किए जा सकते हैं:
<
से कम<=
less than or equal to==
equal to>
से ज़्यादा>=
से ज़्यादा या इसके बराबर!=
not equal toarray-contains
array-contains-any
in
not-in
उदाहरण के लिए:
const stateQuery = query(citiesRef, where("state", "==", "CA")); const populationQuery = query(citiesRef, where("population", "<", 100000)); const nameQuery = query(citiesRef, where("name", ">=", "San Francisco"));
const stateQuery = citiesRef.where("state", "==", "CA"); const populationQuery = citiesRef.where("population", "<", 100000); const nameQuery = citiesRef.where("name", ">=", "San Francisco");
let stateQuery = citiesRef.whereField("state", isEqualTo: "CA") let populationQuery = citiesRef.whereField("population", isLessThan: 100000) let nameQuery = citiesRef.whereField("name", isGreaterThanOrEqualTo: "San Francisco")
FIRQuery *stateQuery = [citiesRef queryWhereField:@"state" isEqualTo:@"CA"]; FIRQuery *populationQuery = [citiesRef queryWhereField:@"population" isLessThan:@100000]; FIRQuery *nameQuery = [citiesRef queryWhereField:@"name" isGreaterThanOrEqualTo:@"San Francisco"];
val stateQuery = citiesRef.whereEqualTo("state", "CA") val populationQuery = citiesRef.whereLessThan("population", 100000) val nameQuery = citiesRef.whereGreaterThanOrEqualTo("name", "San Francisco")
Query stateQuery = citiesRef.whereEqualTo("state", "CA"); Query populationQuery = citiesRef.whereLessThan("population", 100000); Query nameQuery = citiesRef.whereGreaterThanOrEqualTo("name", "San Francisco");
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");
cities_ref.WhereEqualTo("state", FieldValue::String("CA")); cities_ref.WhereLessThan("population", FieldValue::Integer(100000)); cities_ref.WhereGreaterThanOrEqualTo("name", FieldValue::String("San Francisco"));
Query stateQuery = citiesRef.WhereEqualTo("State", "CA"); Query populationQuery = citiesRef.WhereGreaterThan("Population", 1000000); Query nameQuery = citiesRef.WhereGreaterThanOrEqualTo("Name", "San Francisco");
बराबर नहीं है (!=
)
ऐसे दस्तावेज़ों को दिखाने के लिए, 'बराबर नहीं है' (!=
) ऑपरेटर का इस्तेमाल करें जिनमें दिया गया फ़ील्ड मौजूद है और तुलना की वैल्यू से मेल नहीं खाता. उदाहरण के लिए:
const notCapitalQuery = query(citiesRef, where("capital", "!=", false));
citiesRef.where("capital", "!=", false);
let notEqualQuery = citiesRef.whereField("capital", isNotEqualTo: false)
query = [citiesRef queryWhereField:@"capital" isNotEqualTo:@NO];
val notCapitalQuery = citiesRef.whereNotEqualTo("capital", false)
Query notCapitalQuery = citiesRef.whereNotEqualTo("capital", false);
final citiesRef = db.collection("cities"); final notCapitals = citiesRef.where("capital", isNotEqualTo: true);
// Snippet not yet available
cities_ref.WhereNotEqualTo("capital", FieldValue::Boolean(false));
// Snippet not yet available
Query query = citiesRef.WhereNotEqualTo("capital", false); Query query = citiesRef.WhereNotEqualTo("capital", false);
// Snippet not yet available
यह क्वेरी, हर उस city
दस्तावेज़ को दिखाती है जिसमें capital
फ़ील्ड मौजूद है और उसकी वैल्यू false
या null
के अलावा कोई और है. इसमें ऐसे city
दस्तावेज़ शामिल हैं जिनमें capital
फ़ील्ड की वैल्यू true
या null
के अलावा कोई भी नॉन-बूलियन वैल्यू है.
यह क्वेरी, ऐसे city
दस्तावेज़ नहीं दिखाती है जिनमें capital
फ़ील्ड मौजूद नहीं है. बराबर नहीं है (!=
) और not-in
क्वेरी में ऐसे दस्तावेज़ शामिल नहीं होते जिनमें दिया गया फ़ील्ड मौजूद नहीं होता.
कोई फ़ील्ड तब मौजूद होता है, जब उसे किसी वैल्यू पर सेट किया गया हो. इसमें खाली स्ट्रिंग (""
),
null
, और NaN
(यह कोई संख्या नहीं है) शामिल है. ध्यान दें कि null
फ़ील्ड की वैल्यू, !=
क्लॉज़ से मेल नहीं खाती हैं, क्योंकि x != null
का आकलन undefined
के तौर पर किया जाता है.
सीमाएं
!=
क्वेरी के लिए, इन सीमाओं का ध्यान रखें:
- सिर्फ़ वे दस्तावेज़ क्वेरी से मैच कर सकते हैं जिनमें दिया गया फ़ील्ड मौजूद है.
- कंपाउंड क्वेरी में
not-in
और!=
को एक साथ नहीं जोड़ा जा सकता.
पैसे चुकाकर ली जाने वाली सदस्यता
ऐरे वैल्यू के आधार पर फ़िल्टर करने के लिए, array-contains
ऑपरेटर का इस्तेमाल किया जा सकता है. उदाहरण के लिए:
import { query, where } from "firebase/firestore"; const q = query(citiesRef, where("regions", "array-contains", "west_coast"));
citiesRef.where("regions", "array-contains", "west_coast");
citiesRef .whereField("regions", arrayContains: "west_coast")
[citiesRef queryWhereField:@"state" arrayContains:@"west_coast"];
val citiesRef = db.collection("cities") citiesRef.whereArrayContains("regions", "west_coast")
CollectionReference citiesRef = db.collection("cities"); citiesRef.whereArrayContains("regions", "west_coast");
final citiesRef = db.collection("cities"); final westCoastcities = citiesRef.where("regions", arrayContains: "west_coast");
CollectionReference cities_ref = db->Collection("cities"); cities_ref.WhereArrayContains("region", FieldValue::String("west_coast"));
CollectionReference citiesRef = db.Collection("cities"); Query arrayContainsQuery = citiesRef.WhereArrayContains("region", "west_coast");
यह क्वेरी हर उस city
दस्तावेज़ को दिखाती है जिसमें regions
फ़ील्ड एक कलेक्शन होता है और उसमें west_coast
शामिल होता है. अगर ऐरे में उस वैल्यू के कई इंस्टेंस हैं जिस पर आपने क्वेरी की है, तो दस्तावेज़ को नतीजों में सिर्फ़ एक बार शामिल किया जाता है.
हर डिसजंक्शन (or
ग्रुप) के लिए, ज़्यादा से ज़्यादा एक array-contains
क्लॉज़ का इस्तेमाल किया जा सकता है.
एक ही डिसजंक्शन में, array-contains
और array-contains-any
को एक साथ नहीं जोड़ा जा सकता.
in
, not-in
, और array-contains-any
एक ही फ़ील्ड में, लॉजिकल OR
के साथ ज़्यादा से ज़्यादा 30 समानता (==
) वाले क्लॉज़ को जोड़ने के लिए, in
ऑपरेटर का इस्तेमाल करें. in
क्वेरी, ऐसे दस्तावेज़ दिखाती है जिनमें दिया गया फ़ील्ड, तुलना की गई किसी भी वैल्यू से मेल खाता हो.
उदाहरण के लिए:
import { query, where } from "firebase/firestore"; const q = query(citiesRef, where('country', 'in', ['USA', 'Japan']));
citiesRef.where('country', 'in', ['USA', 'Japan']);
let citiesRef = db.collection("cities") citiesRef.whereField("country", in: ["USA", "Japan"])
FIRCollectionReference *citiesRef = [self.db collectionWithPath:@"cities"]; [citiesRef queryWhereField:@"country" in:@[@"USA", @"Japan"]];
val citiesRef = db.collection("cities") citiesRef.whereIn("country", listOf("USA", "Japan"))
CollectionReference citiesRef = db.collection("cities"); citiesRef.whereIn("country", Arrays.asList("USA", "Japan"));
final citiesRef = db.collection("cities"); final cities = citiesRef.where("country", whereIn: ["USA", "Japan"]);
CollectionReference cities_ref = db->Collection("cities"); cities_ref.WhereIn("country", std::vector<FieldValue> { FieldValue::String("USA"), FieldValue::String("Japan") });
CollectionReference citiesRef = db.Collection("cities"); ListcountriesList = new List<object>() {"USA", "Japan"}; Query whereInQuery = citiesRef.WhereIn("country", countriesList);
यह क्वेरी, हर उस city
दस्तावेज़ को दिखाती है जिसमें country
फ़ील्ड को USA
या Japan
पर सेट किया गया है. उदाहरण के तौर पर दिए गए डेटा में, SF
, LA
, DC
, और TOK
दस्तावेज़ शामिल हैं.
not-in
एक ही फ़ील्ड में, 10 तक के 'बराबर नहीं है' (!=
) क्लॉज़ को लॉजिकल AND
के साथ जोड़ने के लिए, not-in
ऑपरेटर का इस्तेमाल करें. not-in
क्वेरी, ऐसे दस्तावेज़ दिखाती है जिनमें दिया गया फ़ील्ड मौजूद है, जो null
नहीं है, और तुलना की गई किसी भी वैल्यू से मेल नहीं खाता. उदाहरण के लिए:
import { query, where } from "firebase/firestore"; const q = query(citiesRef, where('country', 'not-in', ['USA', 'Japan']));
citiesRef.where('country', 'not-in', ['USA', 'Japan']);
citiesRef.whereField("country", notIn: ["USA", "Japan"])
[citiesRef queryWhereField:@"country" notIn:@[@"USA", @"Japan"]];
citiesRef.whereNotIn("country", listOf("USA", "Japan"))
citiesRef.whereNotIn("country", Arrays.asList("USA", "Japan"));
final citiesRef = db.collection("cities"); final cities = citiesRef.where("country", whereNotIn: ["USA", "Japan"]);
// Snippet not yet available
cities_ref.WhereNotIn("country", std::vector<FieldValue> { FieldValue::String("USA"), FieldValue::String("Japan") });
// Snippet not yet available
Query query = citiesRef.WhereNotIn(new FieldPath("country"), new List<string>{"USA", "Japan"}); Query query = citiesRef.WhereNotIn("country", new List<object>(){"USA", "Japan"});
// Snippet not yet available
यह क्वेरी हर उस city
दस्तावेज़ को दिखाती है जिसमें country
फ़ील्ड मौजूद है और वह USA
, Japan
या null
पर सेट नहीं है. उदाहरण के तौर पर दिए गए डेटा में, London
और Hong Kong
दस्तावेज़ शामिल हैं.
not-in
क्वेरी में ऐसे दस्तावेज़ शामिल नहीं होते जिनमें दिया गया फ़ील्ड मौजूद नहीं होता. कोई फ़ील्ड तब मौजूद होता है, जब उसे किसी वैल्यू पर सेट किया गया हो. इसमें खाली स्ट्रिंग (""
), null
, और NaN
(यह कोई संख्या नहीं है) शामिल है. ध्यान दें कि x != null
का आकलन undefined
के तौर पर किया जाता है. तुलना की वैल्यू के तौर पर null
वाली not-in
क्वेरी, किसी भी दस्तावेज़ से मेल नहीं खाती.
array-contains-any
एक ही फ़ील्ड में, लॉजिकल OR
के साथ ज़्यादा से ज़्यादा 30
array-contains
क्लॉज़ को जोड़ने के लिए, array-contains-any
ऑपरेटर का इस्तेमाल करें. array-contains-any
क्वेरी, ऐसे दस्तावेज़ दिखाती है जिनमें दिया गया फ़ील्ड एक कलेक्शन होता है और उसमें तुलना की एक या उससे ज़्यादा वैल्यू शामिल होती हैं:
import { query, where } from "firebase/firestore"; const q = query(citiesRef, where('regions', 'array-contains-any', ['west_coast', 'east_coast']));
citiesRef.where('regions', 'array-contains-any', ['west_coast', 'east_coast']);
let citiesRef = db.collection("cities") citiesRef.whereField("regions", arrayContainsAny: ["west_coast", "east_coast"])
FIRCollectionReference *citiesRef = [self.db collectionWithPath:@"cities"]; [citiesRef queryWhereField:@"regions" arrayContainsAny:@[@"west_coast", @"east_coast"]];
val citiesRef = db.collection("cities") citiesRef.whereArrayContainsAny("regions", listOf("west_coast", "east_coast"))
CollectionReference citiesRef = db.collection("cities"); citiesRef.whereArrayContainsAny("regions", Arrays.asList("west_coast", "east_coast"));
final citiesRef = db.collection("cities"); final cities = citiesRef .where("regions", arrayContainsAny: ["west_coast", "east_coast"]);
CollectionReference cities_ref = db->Collection("cities"); cities_ref.WhereArrayContainsAny("region", std::vector<FieldValue> { FieldValue::String("west_coast"), FieldValue::String("east_coast") });
Query query = citiesRef.WhereArrayContainsAny( "regions", new List<object>() { new List<object>(){"west_coast"}, new List<object>(){"east_coast"}});
यह क्वेरी, हर उस शहर का दस्तावेज़ दिखाती है जहां regions
फ़ील्ड एक ऐरे है और उसमें west_coast
या east_coast
शामिल है. उदाहरण के तौर पर दिए गए डेटा में, SF
, LA
, और DC
दस्तावेज़ शामिल हैं.
array-contains-any
से मिले नतीजों में डुप्लीकेट कॉपी नहीं होतीं. भले ही, किसी दस्तावेज़ का ऐरे फ़ील्ड, तुलना की एक से ज़्यादा वैल्यू से मैच करता हो, लेकिन नतीजे के सेट में उस दस्तावेज़ को सिर्फ़ एक बार शामिल किया जाता है.
array-contains-any
हमेशा ऐरे डेटा टाइप के हिसाब से फ़िल्टर करता है. उदाहरण के लिए, ऊपर दी गई क्वेरी से, शहर का कोई ऐसा दस्तावेज़ नहीं मिलेगा जिसमें अरे के बजाय, regions
फ़ील्ड में स्ट्रिंग west_coast
हो.
in
के लिए, कंपैरिज़न वैल्यू के तौर पर ऐरे वैल्यू का इस्तेमाल किया जा सकता है. हालांकि, array-contains-any
के क्लॉज़ के उलट, यह क्लॉज़ ऐरे की लंबाई, क्रम, और वैल्यू के एग्ज़ैक्ट मैच के लिए मैच करता है. उदाहरण के लिए:
import { query, where } from "firebase/firestore"; const q = query(citiesRef, where('regions', 'in', [['west_coast'], ['east_coast']]));
citiesRef.where('regions', 'in', [['west_coast'], ['east_coast']]);
citiesRef.whereField("regions", in: [["west_coast"], ["east_coast"]])
[citiesRef queryWhereField:@"regions" in:@[@[@"west_coast"], @[@"east_coast"]]];
citiesRef.whereIn("regions", listOf(arrayOf("west_coast"), arrayOf("east_coast")))
citiesRef.whereIn("regions", Arrays.asList(new String[]{"west_coast"}, new String[]{"east_coast"}));
final citiesRef = db.collection("cities"); final cities = citiesRef.where("regions", whereIn: [ ["west_coast"], ["east_coast"] ]);
cities_ref.WhereIn("region", std::vector<FieldValue> { FieldValue::String("west_coast"), FieldValue::String("east_coast") });
Query query = citiesRef.WhereIn(new FieldPath("regions"), new List<string>{"west_coast", "east_coast"});
यह क्वेरी, हर उस शहर का दस्तावेज़ दिखाती है जहां regions
फ़ील्ड एक कलेक्शन है और उसमें west_coast
या east_coast
में से कोई एक एलिमेंट मौजूद है.
उदाहरण के तौर पर दिए गए डेटा में, सिर्फ़ DC
दस्तावेज़ ["east_coast"]
के regions
फ़ील्ड के साथ मेल खाता है. हालांकि, SF
दस्तावेज़ मैच नहीं करता, क्योंकि उसका regions
फ़ील्ड ["west_coast", "norcal"]
है.
सीमाएं
in
, not-in
, और array-contains-any
के लिए, इन सीमाओं का ध्यान रखें:
- Cloud Firestore,
or
,in
, औरarray-contains-any
ऑपरेटर की मदद से, लॉजिकलOR
क्वेरी के लिए सहायता उपलब्ध कराता है. इन क्वेरी में, क्वेरी के डिसजंक्टिव नॉर्मल फ़ॉर्म के आधार पर 30 डिसजंक्शन तक ही इस्तेमाल किए जा सकते हैं. - हर डिसजंक्शन (
or
ग्रुप) के लिए, ज़्यादा से ज़्यादा एकarray-contains
क्लॉज़ का इस्तेमाल किया जा सकता है. एक ही डिसजंक्शन में,array-contains
औरarray-contains-any
को एक साथ नहीं जोड़ा जा सकता. not-in
को 'बराबर नहीं है'!=
के साथ नहीं जोड़ा जा सकता.not-in
फ़ंक्शन में, तुलना के लिए ज़्यादा से ज़्यादा 10 वैल्यू इस्तेमाल की जा सकती हैं.
कंपाउंड (AND
) क्वेरी
एक से ज़्यादा इक्वलिटी ऑपरेटर (==
या array-contains
) को चेन करके, लॉजिकल AND
के साथ पाबंदियों को जोड़ा जा सकता है. हालांकि, इक्वलिटी ऑपरेटर को इनइक्वलिटी ऑपरेटर, <
, <=
, >
, और !=
के साथ जोड़ने के लिए, आपको एक कंपोज़िट इंडेक्स बनाना होगा.
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));
const q1 = citiesRef.where("state", "==", "CO").where("name", "==", "Denver"); const q2 = citiesRef.where("state", "==", "CA").where("population", "<", 1000000);
citiesRef .whereField("state", isEqualTo: "CO") .whereField("name", isEqualTo: "Denver") citiesRef .whereField("state", isEqualTo: "CA") .whereField("population", isLessThan: 1000000)
[[citiesRef queryWhereField:@"state" isEqualTo:@"CO"] queryWhereField:@"name" isGreaterThanOrEqualTo:@"Denver"]; [[citiesRef queryWhereField:@"state" isEqualTo:@"CA"] queryWhereField:@"population" isLessThan:@1000000];
citiesRef.whereEqualTo("state", "CO").whereEqualTo("name", "Denver") citiesRef.whereEqualTo("state", "CA").whereLessThan("population", 1000000)
citiesRef.whereEqualTo("state", "CO").whereEqualTo("name", "Denver"); citiesRef.whereEqualTo("state", "CA").whereLessThan("population", 1000000);
final citiesRef = db.collection("cities"); citiesRef .where("state", isEqualTo: "CO") .where("name", isEqualTo: "Denver"); citiesRef .where("state", isEqualTo: "CA") .where("population", isLessThan: 1000000);
cities_ref.WhereEqualTo("state", FieldValue::String("CO")) .WhereEqualTo("name", FieldValue::String("Denver")); cities_ref.WhereEqualTo("state", FieldValue::String("CA")) .WhereLessThan("population", FieldValue::Integer(1000000));
Query chainedQuery = citiesRef .WhereEqualTo("State", "CA") .WhereEqualTo("Name", "San Francisco");
OR
क्वेरी
सीमाओं को लॉजिकल OR
के साथ जोड़ा जा सकता है. उदाहरण के लिए:
const q = query(citiesRef, or(where('capital', '==', true), where('population', '>=', 1000000) ) );
उपलब्ध नहीं है.
let query = db.collection("cities").whereFilter(Filter.orFilter([ Filter.whereField("capital", isEqualTo: true), Filter.whereField("population", isGreaterThanOrEqualTo: 1000000); ]))
FIRCollectionReference *collection = [self.db collectionWithPath:@"cities"]; FIRQuery *query = [collection queryWhereFilter:[FIRFilter orFilterWithFilters:@[ [FIRFilter filterWhereField:@"capital" isEqualTo:@YES], [FIRFilter filterWhereField:@"population" isGreaterThanOrEqualTo:@1000000] ]]];
val query = collection.where(Filter.or( Filter.equalTo("capital", true), Filter.greaterThanOrEqualTo("population", 1000000) ))
Query query = collection.where(Filter.or( Filter.equalTo("capital", true), Filter.greaterThanOrEqualTo("population", 1000000) ));
var query = db.collection("cities").where( Filter.or( Filter("capital", isEqualTo: true), Filter("population", isGreaterThan: 1000000), ), );
स्निपेट उपलब्ध नहीं है.
स्निपेट उपलब्ध नहीं है.
स्निपेट उपलब्ध नहीं है.
const bigCities = await citiesRef .where( Filter.or( Filter.where('capital', '==', true), Filter.where('population', '>=', 1000000) ) ) .get();
स्निपेट उपलब्ध नहीं है.
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)); } });
स्निपेट उपलब्ध नहीं है.
स्निपेट उपलब्ध नहीं है.
Cloud Firestore, OR
क्वेरी दिखाने के लिए आपके कंपोजिट इंडेक्स का इस्तेमाल करता है. अगर आपके इंडेक्स, क्वेरी के साथ काम नहीं करते, तो Cloud Firestore
आपके डेटाबेस के लिए अन्य इंडेक्स के सुझाव देता है.
OR
और AND
ऑपरेशन के कॉम्बिनेशन के हिसाब से फ़िल्टर करने के लिए, OR
क्वेरी को कंपाउंड क्वेरी के साथ जोड़ा जा सकता है. उदाहरण के लिए:
const q = query(collection(db, "cities"), and( where('state', '==', 'CA'), or( where('capital', '==', true), where('population', '>=', 1000000) ) ));
उपलब्ध नहीं है.
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) ]) ]))
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] ]] ]]];
val query = collection.where(Filter.and( Filter.equalTo("state", "CA"), Filter.or( Filter.equalTo("capital", true), Filter.greaterThanOrEqualTo("population", 1000000) ) ))
Query query = collection.where(Filter.and( Filter.equalTo("state", "CA"), Filter.or( Filter.equalTo("capital", true), Filter.greaterThanOrEqualTo("population", 1000000) ) ));
var query = db.collection("cities").where( Filter.and( Filter("state", isEqualTo: "CA"), Filter.or( Filter("capital", isEqualTo: true), Filter("population", isGreaterThan: 1000000), ), ), );
स्निपेट उपलब्ध नहीं है.
स्निपेट उपलब्ध नहीं है.
स्निपेट उपलब्ध नहीं है.
स्निपेट उपलब्ध नहीं है.
const bigCitiesInCalifornia = await citiesRef .where('state', '==', 'CA') .where( Filter.or( Filter.where('capital', '==', true), Filter.where('population', '>=', 1000000) ) ) .get();
स्निपेट उपलब्ध नहीं है.
स्निपेट उपलब्ध नहीं है.
Query query = citiesRef.Where(Filter.And( Filter.EqualTo("state", "CA"), Filter.Or( Filter.EqualTo("capital", true), Filter.GreaterThanOrEqualTo("population", 1000000) ) ));
स्निपेट उपलब्ध नहीं है.
स्निपेट उपलब्ध नहीं है.
सीमाएं
or
क्वेरी के लिए, इन सीमाओं का ध्यान रखें:
- Cloud Firestore, क्वेरी के डिसजंक्टिव नॉर्मल फ़ॉर्म के आधार पर, क्वेरी को ज़्यादा से ज़्यादा 30 डिसजंक्शन तक सीमित करता है.
एक से ज़्यादा
OR
ग्रुप काAND
करने पर, इस सीमा तक पहुंचने की संभावना ज़्यादा होती है. - एक ही क्वेरी में
not-in
कोin
,array-contains-any
याor
के साथ नहीं जोड़ा जा सकता.
सीमाओं के बारे में पूरी जानकारी के लिए, क्वेरी की सीमाएं देखें.
कलेक्शन ग्रुप की क्वेरी
कलेक्शन ग्रुप में, एक ही आईडी वाले सभी कलेक्शन शामिल होते हैं. डिफ़ॉल्ट रूप से, क्वेरी आपके डेटाबेस के किसी एक कलेक्शन से नतीजे दिखाती हैं. किसी एक कलेक्शन के बजाय, कलेक्शन ग्रुप से दस्तावेज़ पाने के लिए, कलेक्शन ग्रुप क्वेरी का इस्तेमाल करें.
उदाहरण के लिए, हर शहर में लैंडमार्क का सबकलेक्शन जोड़कर, landmarks
कलेक्शन ग्रुप बनाया जा सकता है:
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' }) ]);
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' }) ]);
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)
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];
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)
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);
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);
// 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;
}
});
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;
किसी एक शहर के landmarks
सब-कलेक्शन के लिए क्वेरी करने के लिए, हम ऊपर बताई गई सिंपल और कंपाउंड क्वेरी का इस्तेमाल कर सकते हैं. हालांकि, हो सकता है कि आप हर शहर के landmarks
सब-कलेक्शन से एक साथ नतीजे पाना चाहें.
landmarks
कलेक्शन ग्रुप में, आईडी landmarks
वाले सभी कलेक्शन शामिल होते हैं. साथ ही, कलेक्शन ग्रुप क्वेरी का इस्तेमाल करके, इसकी क्वेरी की जा सकती है. उदाहरण के लिए,
यह कलेक्शन ग्रुप क्वेरी, सभी शहरों के सभी museum
लैंडमार्क को वापस लाती है:
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()); });
var museums = db.collectionGroup('landmarks').where('type', '==', 'museum'); museums.get().then((querySnapshot) => { querySnapshot.forEach((doc) => { console.log(doc.id, ' => ', doc.data()); }); });
db.collectionGroup("landmarks").whereField("type", isEqualTo: "museum").getDocuments { (snapshot, error) in // ... }
[[[self.db collectionGroupWithID:@"landmarks"] queryWhereField:@"type" isEqualTo:@"museum"] getDocumentsWithCompletion:^(FIRQuerySnapshot *snapshot, NSError *error) { // ... }];
db.collectionGroup("landmarks").whereEqualTo("type", "museum").get() .addOnSuccessListener { queryDocumentSnapshots -> // ... }
db.collectionGroup("landmarks").whereEqualTo("type", "museum").get() .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() { @Override public void onSuccess(QuerySnapshot queryDocumentSnapshots) { // ... } });
db .collectionGroup("landmarks") .where("type", isEqualTo: "museum") .get() .then( (res) => print("Successfully completed"), onError: (e) => print("Error completing: $e"), );
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;
}
});
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)); } });
कलेक्शन ग्रुप क्वेरी का इस्तेमाल करने से पहले, आपको एक ऐसा इंडेक्स बनाना होगा जो आपकी कलेक्शन ग्रुप क्वेरी के साथ काम करता हो. गड़बड़ी के मैसेज, कंसोल या Firebase CLI की मदद से इंडेक्स बनाया जा सकता है.
वेब और मोबाइल SDK टूल के लिए, आपको ऐसे नियम भी बनाने होंगे जिनसे आपके कलेक्शन ग्रुप की क्वेरी को अनुमति मिल सके.
क्वेरी की परफ़ॉर्मेंस के बारे में बताना
Cloud Firestore की मदद से, बैकएंड पर अपनी क्वेरी की परफ़ॉर्मेंस का आकलन किया जा सकता है. साथ ही, बैकएंड क्वेरी के एक्सीक्यूशन पर परफ़ॉर्मेंस के बारे में ज़्यादा जानकारी वाले आंकड़े भी मिल सकते हैं.
क्वेरी एक्सप्लेन के नतीजों से, आपको यह समझने में मदद मिलती है कि आपकी क्वेरी कैसे लागू की जाती हैं. साथ ही, इससे आपको क्वेरी के खराब परफ़ॉर्म करने की वजहें और सर्वर साइड की समस्याओं की जगह के बारे में पता चलता है.
ज़्यादा जानकारी के लिए, क्वेरी एक्सप्लेन के लिए गाइड देखें.
क्वेरी से जुड़ी सीमाएं
यहां दी गई सूची में, Cloud Firestore क्वेरी की सीमाओं के बारे में खास जानकारी दी गई है:
- Cloud Firestore,
or
,in
, औरarray-contains-any
ऑपरेटर की मदद से, लॉजिकलOR
क्वेरी के लिए सहायता उपलब्ध कराता है. इन क्वेरी में, क्वेरी के डिसजंक्टिव नॉर्मल फ़ॉर्म के आधार पर 30 डिसजंक्शन तक ही इस्तेमाल किए जा सकते हैं. - हर डिसजंक्शन (
or
ग्रुप) के लिए, ज़्यादा से ज़्यादा एकarray-contains
क्लॉज़ का इस्तेमाल किया जा सकता है. एक ही डिसजंक्शन में,array-contains
औरarray-contains-any
को एक साथ नहीं जोड़ा जा सकता. - एक ही क्वेरी में
not-in
कोin
,array-contains-any
याor
के साथ नहीं जोड़ा जा सकता. - हर क्वेरी के लिए सिर्फ़ एक
not-in
या!=
इस्तेमाल किया जा सकता है. not-in
फ़ंक्शन में, तुलना के लिए ज़्यादा से ज़्यादा 10 वैल्यू इस्तेमाल की जा सकती हैं.- किसी क्वेरी में फ़िल्टर, क्रम से लगाने के तरीकों, और पेरंट दस्तावेज़ के पाथ (सब-कलेक्शन के लिए 1, रूट कलेक्शन के लिए 0) का कुल योग 100 से ज़्यादा नहीं हो सकता. इसका हिसाब, क्वेरी के डिसकंजंटिव नॉर्मल फ़ॉर्म के आधार पर लगाया जाता है.
- किसी फ़ील्ड पर असमानता फ़िल्टर वाली क्वेरी का मतलब है कि उस फ़ील्ड के हिसाब से क्रम तय किया गया है और उस फ़ील्ड के मौजूद होने के लिए फ़िल्टर लागू किए गए हैं.
OR
क्वेरी की सीमाएं
क्वेरी को बहुत ज़्यादा कंप्यूटेशनल खर्च से बचाने के लिए,
Cloud Firestore यह तय करता है कि कितने AND
और OR
क्लॉज़ को आपस में जोड़ा जा सकता है.
यह सीमा लागू करने के लिए, Cloud Firestore उन क्वेरी को डिसजंक्टिव नॉर्मल फ़ॉर्म में बदल देता है जो लॉजिकल OR
ऑपरेशन (or
, in
, और array-contains-any
) करते हैं. इसे AND
s का OR
भी कहा जाता है. Cloud Firestore, डिसजंक्टिव नॉर्मल फ़ॉर्म में किसी क्वेरी को ज़्यादा से ज़्यादा 30 डिसजंक्शन तक सीमित करता है.
डिसकंजंटिव नॉर्मल फ़ॉर्म
Cloud Firestore दो नियमों को लागू करके, क्वेरी को डिसजंक्टिव नॉर्मल फ़ॉर्म में बदलता है:
फ़्लैट करें
A
,B
, औरC
की शर्तों के मुताबिक:A and (B and C) => A and B and C
-
दी गई शर्तें
A
,B
,C
, औरD
: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)
in
और array-contains-any
क्वेरी पर ये नियम लागू करते समय, याद रखें कि ये ऑपरेटर OR
के लिए शॉर्टहैंड हैं. उदाहरण के लिए, a in [1,2]
, a = 1 OR a = 2
का शॉर्टहैंड है.
नीचे दिए गए उदाहरणों में, अलग-अलग क्वेरी के लिए डिसजंक्शन की संख्या दिखाई गई है:
क्वेरी | डिसजंक्शन की संख्या |
---|---|
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 इस क्वेरी का डिसकंजंटिव नॉर्मल फ़ॉर्म, ऊपर दी गई क्वेरी के बराबर है. |
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 यह क्वेरी गड़बड़ी दिखाती है, क्योंकि इसमें 30 डिसजंक्शन से ज़्यादा हैं. |
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
और मौजूदगी
किसी फ़ील्ड के हिसाब से क्वेरी को क्रम में लगाने पर, क्वेरी सिर्फ़ उन दस्तावेज़ों को दिखा सकती है जिनमें क्रम से लगाने के लिए फ़ील्ड मौजूद है.
उदाहरण के लिए, नीचे दी गई क्वेरी से ऐसे किसी भी दस्तावेज़ का नतीजा नहीं मिलेगा जिसमें population
फ़ील्ड सेट न हो. भले ही, वह क्वेरी फ़िल्टर से मेल खाता हो.
db.collection("cities").whereEqualTo("country", “USA”).orderBy(“population”);
असमानताओं पर भी इसी तरह का असर पड़ता है. किसी फ़ील्ड पर, असमानता वाले फ़िल्टर वाली क्वेरी का मतलब उस फ़ील्ड के हिसाब से क्रम से लगाने से भी है. यहां दी गई क्वेरी से, ऐसे दस्तावेज़ नहीं मिलते जिनमें population
फ़ील्ड मौजूद न हो. भले ही, उस दस्तावेज़ में country = USA
मौजूद हो. इस समस्या को हल करने के लिए, हर क्रम के लिए अलग-अलग क्वेरी चलाई जा सकती हैं. इसके अलावा, उन सभी फ़ील्ड के लिए वैल्यू असाइन की जा सकती है जिनके हिसाब से क्रम तय किया जाता है.
db.collection(“cities”).where(or(“country”, USA”), greaterThan(“population”, 250000));
ऊपर दी गई क्वेरी में, असमानता के आधार पर क्रम से लगाने का अनुरोध शामिल है. यह क्वेरी, यहां दी गई क्वेरी के बराबर है:
db.collection(“cities”).where(or(“country”, USA”), greaterThan(“population”, 250000)).orderBy(“population”);
आगे क्या करना है
- क्वेरी के नतीजों में डेटा को क्रम से लगाने और सीमित करने का तरीका जानें.
- अगर आपको सिर्फ़ नतीजों की गिनती करनी है, तो रीड को सेव करें.