Perform simple and compound queries in Cloud Firestore

Cloud Firestore provides powerful query functionality for specifying whichdocuments you want to retrieve from a collection or collection group. Thesequeries can also be used with eitherget() oraddSnapshotListener(), asdescribed inGet Data andGet Realtime Updates.

Note: While the code samples cover multiple languages, the text explaining thesamples refers to the Web method names.

Example data

To get started, write some data about cities so we can look at different ways toread it back:

Web

import{collection,doc,setDoc}from"firebase/firestore";constcitiesRef=collection(db,"cities");awaitsetDoc(doc(citiesRef,"SF"),{name:"San Francisco",state:"CA",country:"USA",capital:false,population:860000,regions:["west_coast","norcal"]});awaitsetDoc(doc(citiesRef,"LA"),{name:"Los Angeles",state:"CA",country:"USA",capital:false,population:3900000,regions:["west_coast","socal"]});awaitsetDoc(doc(citiesRef,"DC"),{name:"Washington, D.C.",state:null,country:"USA",capital:true,population:680000,regions:["east_coast"]});awaitsetDoc(doc(citiesRef,"TOK"),{name:"Tokyo",state:null,country:"Japan",capital:true,population:9000000,regions:["kanto","honshu"]});awaitsetDoc(doc(citiesRef,"BJ"),{name:"Beijing",state:null,country:"China",capital:true,population:21500000,regions:["jingjinji","hebei"]});

Web

Learn more about the tree-shakeable modular Web API and its advantages over the namespaced API.
varcitiesRef=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"]});
Swift
Note: This product is not available on watchOS and App Clip targets.
letcitiesRef=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"]])
Objective-C
Note: This product is not available on watchOS and App Clip targets.
FIRCollectionReference*citiesRef=[self.dbcollectionWithPath:@"cities"];[[citiesRefdocumentWithPath:@"SF"]setData:@{@"name":@"San Francisco",@"state":@"CA",@"country":@"USA",@"capital":@(NO),@"population":@860000,@"regions":@[@"west_coast",@"norcal"]}];[[citiesRefdocumentWithPath:@"LA"]setData:@{@"name":@"Los Angeles",@"state":@"CA",@"country":@"USA",@"capital":@(NO),@"population":@3900000,@"regions":@[@"west_coast",@"socal"]}];[[citiesRefdocumentWithPath:@"DC"]setData:@{@"name":@"Washington D.C.",@"country":@"USA",@"capital":@(YES),@"population":@680000,@"regions":@[@"east_coast"]}];[[citiesRefdocumentWithPath:@"TOK"]setData:@{@"name":@"Tokyo",@"country":@"Japan",@"capital":@(YES),@"population":@9000000,@"regions":@[@"kanto",@"honshu"]}];[[citiesRefdocumentWithPath:@"BJ"]setData:@{@"name":@"Beijing",@"country":@"China",@"capital":@(YES),@"population":@21500000,@"regions":@[@"jingjinji",@"hebei"]}];

Kotlin

valcities=db.collection("cities")valdata1=hashMapOf("name"to"San Francisco","state"to"CA","country"to"USA","capital"tofalse,"population"to860000,"regions"tolistOf("west_coast","norcal"),)cities.document("SF").set(data1)valdata2=hashMapOf("name"to"Los Angeles","state"to"CA","country"to"USA","capital"tofalse,"population"to3900000,"regions"tolistOf("west_coast","socal"),)cities.document("LA").set(data2)valdata3=hashMapOf("name"to"Washington D.C.","state"tonull,"country"to"USA","capital"totrue,"population"to680000,"regions"tolistOf("east_coast"),)cities.document("DC").set(data3)valdata4=hashMapOf("name"to"Tokyo","state"tonull,"country"to"Japan","capital"totrue,"population"to9000000,"regions"tolistOf("kanto","honshu"),)cities.document("TOK").set(data4)valdata5=hashMapOf("name"to"Beijing","state"tonull,"country"to"China","capital"totrue,"population"to21500000,"regions"tolistOf("jingjinji","hebei"),)cities.document("BJ").set(data5)

Java

CollectionReferencecities=db.collection("cities");Map<String,Object>data1=newHashMap<>();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=newHashMap<>();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=newHashMap<>();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=newHashMap<>();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=newHashMap<>();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

finalcities=db.collection("cities");finaldata1=<String,dynamic>{"name":"San Francisco","state":"CA","country":"USA","capital":false,"population":860000,"regions":["west_coast","norcal"]};cities.doc("SF").set(data1);finaldata2=<String,dynamic>{"name":"Los Angeles","state":"CA","country":"USA","capital":false,"population":3900000,"regions":["west_coast","socal"],};cities.doc("LA").set(data2);finaldata3=<String,dynamic>{"name":"Washington D.C.","state":null,"country":"USA","capital":true,"population":680000,"regions":["east_coast"]};cities.doc("DC").set(data3);finaldata4=<String,dynamic>{"name":"Tokyo","state":null,"country":"Japan","capital":true,"population":9000000,"regions":["kanto","honshu"]};cities.doc("TOK").set(data4);finaldata5=<String,dynamic>{"name":"Beijing","state":null,"country":"China","capital":true,"population":21500000,"regions":["jingjinji","hebei"],};cities.doc("BJ").set(data5);
Java
CollectionReferencecities=db.collection("cities");List<ApiFuture<WriteResult>>futures=newArrayList<>();futures.add(cities.document("SF").set(newCity("San Francisco","CA","USA",false,860000L,Arrays.asList("west_coast","norcal"))));futures.add(cities.document("LA").set(newCity("Los Angeles","CA","USA",false,3900000L,Arrays.asList("west_coast","socal"))));futures.add(cities.document("DC").set(newCity("Washington D.C.",null,"USA",true,680000L,Arrays.asList("east_coast"))));futures.add(cities.document("TOK").set(newCity("Tokyo",null,"Japan",true,9000000L,Arrays.asList("kanto","honshu"))));futures.add(cities.document("BJ").set(newCity("Beijing",null,"China",true,21500000L,Arrays.asList("jingjinji","hebei"))));// (optional) block on documents successfully addedApiFutures.allAsList(futures).get();
Python
classCity:def__init__(self,name,state,country,capital=False,population=0,regions=[]):self.name=nameself.state=stateself.country=countryself.capital=capitalself.population=populationself.regions=regions@staticmethoddeffrom_dict(source):# ...defto_dict(self):# ...def__repr__(self):returnf"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

classCity:def__init__(self,name,state,country,capital=False,population=0,regions=[]):self.name=nameself.state=stateself.country=countryself.capital=capitalself.population=populationself.regions=regions@staticmethoddeffrom_dict(source):# ...defto_dict(self):# ...def__repr__(self):returnf"City(\                name={self.name},\                country={self.country},\                population={self.population},\                capital={self.capital},\                regions={self.regions}\            )"
cities_ref=db.collection("cities")awaitcities_ref.document("BJ").set(City("Beijing",None,"China",True,21500000,["hebei"]).to_dict())awaitcities_ref.document("SF").set(City("San Francisco","CA","USA",False,860000,["west_coast","norcal"]).to_dict())awaitcities_ref.document("LA").set(City("Los Angeles","CA","USA",False,3900000,["west_coast","socal"]).to_dict())awaitcities_ref.document("DC").set(City("Washington D.C.",None,"USA",True,680000,["east_coast"]).to_dict())awaitcities_ref.document("TOK").set(City("Tokyo",None,"Japan",True,9000000,["kanto","honshu"]).to_dict())
C++
CollectionReferencecities=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
constcitiesRef=db.collection('cities');awaitcitiesRef.doc('SF').set({name:'San Francisco',state:'CA',country:'USA',capital:false,population:860000,regions:['west_coast','norcal']});awaitcitiesRef.doc('LA').set({name:'Los Angeles',state:'CA',country:'USA',capital:false,population:3900000,regions:['west_coast','socal']});awaitcitiesRef.doc('DC').set({name:'Washington, D.C.',state:null,country:'USA',capital:true,population:680000,regions:['east_coast']});awaitcitiesRef.doc('TOK').set({name:'Tokyo',state:null,country:'Japan',capital:true,population:9000000,regions:['kanto','honshu']});awaitcitiesRef.doc('BJ').set({name:'Beijing',state:null,country:'China',capital:true,population:21500000,regions:['jingjinji','hebei']});
Go
cities:=[]struct{idstringcCity}{{id:"SF",c:City{Name:"San Francisco",State:"CA",Country:"USA",Capital:false,Population:860000,Regions:[]string{"west_coast","norcal"}},},{id:"LA",c:City{Name:"Los Angeles",State:"CA",Country:"USA",Capital:false,Population:3900000,Regions:[]string{"west_coast","socal"}},},{id:"DC",c:City{Name:"Washington D.C.",Country:"USA",Capital:true,Population:680000,Regions:[]string{"east_coast"}},},{id:"TOK",c:City{Name:"Tokyo",Country:"Japan",Capital:true,Population:9000000,Regions:[]string{"kanto","honshu"}},},{id:"BJ",c:City{Name:"Beijing",Country:"China",Capital:true,Population:21500000,Regions:[]string{"jingjinji","hebei"}},},}for_,c:=rangecities{if_,err:=client.Collection("cities").Doc(c.id).Set(ctx,c.c);err!=nil{returnerr}}
PHP
$citiesRef = $db->collection('samples/php/cities');$citiesRef->document('SF')->set([    'name' => 'San Francisco',    'state' => 'CA',    'country' => 'USA',    'capital' => false,    'population' => 860000,    'density' => 18000,    'regions' => ['west_coast', 'norcal']]);$citiesRef->document('LA')->set([    'name' => 'Los Angeles',    'state' => 'CA',    'country' => 'USA',    'capital' => false,    'population' => 3900000,    'density' => 8000,    'regions' => ['west_coast', 'socal']]);$citiesRef->document('DC')->set([    'name' => 'Washington D.C.',    'state' => null,    'country' => 'USA',    'capital' => true,    'population' => 680000,    'density' => 11000,    'regions' => ['east_coast']]);$citiesRef->document('TOK')->set([    'name' => 'Tokyo',    'state' => null,    'country' => 'Japan',    'capital' => true,    'population' => 9000000,    'density' => 16000,    'regions' => ['kanto', 'honshu']]);$citiesRef->document('BJ')->set([    'name' => 'Beijing',    'state' => null,    'country' => 'China',    'capital' => true,    'population' => 21500000,    'density' => 3500,    'regions' => ['jingjinji', 'hebei']]);printf('Added example cities data to the cities collection.' . PHP_EOL);
Unity
CollectionReferencecitiesRef=db.Collection("cities");citiesRef.Document("SF").SetAsync(newDictionary<string,object>(){{"Name","San Francisco"},{"State","CA"},{"Country","USA"},{"Capital",false},{"Population",860000},{"Regions",newArrayList{"west_coast","norcal"}}});citiesRef.Document("LA").SetAsync(newDictionary<string,object>(){{"Name","Los Angeles"},{"State","CA"},{"Country","USA"},{"Capital",false},{"Population",3900000},{"Regions",newArrayList{"west_coast","socal"}}});citiesRef.Document("DC").SetAsync(newDictionary<string,object>(){{"Name","Washington D.C."},{"State",null},{"Country","USA"},{"Capital",true},{"Population",680000},{"Regions",newArrayList{"east_coast"}}});citiesRef.Document("TOK").SetAsync(newDictionary<string,object>(){{"Name","Tokyo"},{"State",null},{"Country","Japan"},{"Capital",true},{"Population",9000000},{"Regions",newArrayList{"kanto","honshu"}}});citiesRef.Document("BJ").SetAsync(newDictionary<string,object>(){{"Name","Beijing"},{"State",null},{"Country","China"},{"Capital",true},{"Population",21500000},{"Regions",newArrayList{"jingjinji","hebei"}}});
C#
CollectionReferencecitiesRef=db.Collection("cities");awaitcitiesRef.Document("SF").SetAsync(newDictionary<string,object>{{"Name","San Francisco"},{"State","CA"},{"Country","USA"},{"Capital",false},{"Population",860000},{"Density",18000},{"Regions",new[]{"west_coast","norcal"}}});awaitcitiesRef.Document("LA").SetAsync(newDictionary<string,object>{{"Name","Los Angeles"},{"State","CA"},{"Country","USA"},{"Capital",false},{"Population",3900000},{"Density",8300},{"Regions",new[]{"west_coast","socal"}}});awaitcitiesRef.Document("DC").SetAsync(newDictionary<string,object>{{"Name","Washington D.C."},{"State",null},{"Country","USA"},{"Capital",true},{"Population",680000},{"Density",11300},{"Regions",new[]{"east_coast"}}});awaitcitiesRef.Document("TOK").SetAsync(newDictionary<string,object>{{"Name","Tokyo"},{"State",null},{"Country","Japan"},{"Capital",true},{"Population",9000000},{"Density",16000},{"Regions",new[]{"kanto","honshu"}}});awaitcitiesRef.Document("BJ").SetAsync(newDictionary<string,object>{{"Name","Beijing"},{"State",null},{"Country","China"},{"Capital",true},{"Population",21500000},{"Density",3500},{"Regions",new[]{"jingjinji","hebei"}}});Console.WriteLine("Added example cities data to the cities collection.");
Ruby
cities_ref=firestore.colcollection_pathcities_ref.doc("SF").set({name:"San Francisco",state:"CA",country:"USA",capital:false,density:18_000,population:860_000,regions:["west_coast","norcal"]})cities_ref.doc("LA").set({name:"Los Angeles",state:"CA",country:"USA",capital:false,density:8_300,population:3_900_000,regions:["west_coast","socal"]})cities_ref.doc("DC").set({name:"Washington D.C.",state:nil,country:"USA",capital:true,density:11_300,population:680_000,regions:["east_coast"]})cities_ref.doc("TOK").set({name:"Tokyo",state:nil,country:"Japan",capital:true,density:16_000,population:9_000_000,regions:["kanto","honshu"]})cities_ref.doc("BJ").set({name:"Beijing",state:nil,country:"China",capital:true,density:3_500,population:21_500_000,regions:["jingjinji","hebei"]})

Simple queries

The following query returns all cities with stateCA:

Web

// Create a reference to the cities collectionimport{collection,query,where}from"firebase/firestore";constcitiesRef=collection(db,"cities");// Create a query against the collection.constq=query(citiesRef,where("state","==","CA"));

Web

Learn more about the tree-shakeable modular Web API and its advantages over the namespaced API.
// Create a reference to the cities collectionvarcitiesRef=db.collection("cities");// Create a query against the collection.varquery=citiesRef.where("state","==","CA");
Swift
Note: This product is not available on watchOS and App Clip targets.
// Create a reference to the cities collectionletcitiesRef=db.collection("cities")// Create a query against the collection.letquery=citiesRef.whereField("state",isEqualTo:"CA")
Objective-C
Note: This product is not available on watchOS and App Clip targets.
// Create a reference to the cities collectionFIRCollectionReference*citiesRef=[self.dbcollectionWithPath:@"cities"];// Create a query against the collection.FIRQuery*query=[citiesRefqueryWhereField:@"state"isEqualTo:@"CA"];

Kotlin

// Create a reference to the cities collectionvalcitiesRef=db.collection("cities")// Create a query against the collection.valquery=citiesRef.whereEqualTo("state","CA")

Java

// Create a reference to the cities collectionCollectionReferencecitiesRef=db.collection("cities");// Create a query against the collection.Queryquery=citiesRef.whereEqualTo("state","CA");

Dart

// Create a reference to the cities collectionfinalcitiesRef=db.collection("cities");// Create a query against the collection.finalquery=citiesRef.where("state",isEqualTo:"CA");
Java
// Create a reference to the cities collectionCollectionReferencecities=db.collection("cities");// Create a query against the collection.Queryquery=cities.whereEqualTo("state","CA");// retrieve  query results asynchronously using query.get()ApiFuture<QuerySnapshot>querySnapshot=query.get();for(DocumentSnapshotdocument:querySnapshot.get().getDocuments()){System.out.println(document.getId());}
Python
# Create a reference to the cities collectioncities_ref=db.collection("cities")# Create a query against the collectionquery_ref=cities_ref.where(filter=FieldFilter("state","==","CA"))

Python

# Create a reference to the cities collectioncities_ref=db.collection("cities")# Create a query against the collectionquery_ref=cities_ref.where(filter=FieldFilter("state","==","CA"))
C++
CollectionReferencecities_ref=db->Collection("cities");// Create a query against the collection.Queryquery_ca=cities_ref.WhereEqualTo("state",FieldValue::String("CA"));
Node.js
// Create a reference to the cities collectionconstcitiesRef=db.collection('cities');// Create a query against the collectionconstqueryRef=citiesRef.where('state','==','CA');
Go
query:=client.Collection("cities").Where("state","==","CA")
PHP
$citiesRef = $db->collection('samples/php/cities');$query = $citiesRef->where('state', '=', 'CA');$snapshot = $query->documents();foreach ($snapshot as $document) {    printf('Document %s returned by query state=CA' . PHP_EOL, $document->id());}
Unity
CollectionReferencecitiesRef=db.Collection("cities");Queryquery=citiesRef.WhereEqualTo("State","CA");query.GetSnapshotAsync().ContinueWithOnMainThread((querySnapshotTask)=>{foreach(DocumentSnapshotdocumentSnapshotinquerySnapshotTask.Result.Documents){Debug.Log(String.Format("Document {0} returned by query State=CA",documentSnapshot.Id));}});
C#
CollectionReferencecitiesRef=db.Collection("cities");Queryquery=citiesRef.WhereEqualTo("State","CA");QuerySnapshotquerySnapshot=awaitquery.GetSnapshotAsync();foreach(DocumentSnapshotdocumentSnapshotinquerySnapshot.Documents){Console.WriteLine("Document {0} returned by query State=CA",documentSnapshot.Id);}
Ruby
cities_ref=firestore.colcollection_pathquery=cities_ref.where"state","=","CA"query.getdo|city|puts"Document#{city.document_id} returned by query state=CA."end

The following query returns all the capital cities:

Web

import{collection,query,where}from"firebase/firestore";constcitiesRef=collection(db,"cities");constq=query(citiesRef,where("capital","==",true));

Web

Learn more about the tree-shakeable modular Web API and its advantages over the namespaced API.
varcitiesRef=db.collection("cities");varquery=citiesRef.where("capital","==",true);
Swift
Note: This product is not available on watchOS and App Clip targets.
letcapitalCities=db.collection("cities").whereField("capital",isEqualTo:true)
Objective-C
Note: This product is not available on watchOS and App Clip targets.
FIRQuery*capitalCities=[[self.dbcollectionWithPath:@"cities"]queryWhereField:@"capital"isEqualTo:@YES];

Kotlin

valcapitalCities=db.collection("cities").whereEqualTo("capital",true)

Java

QuerycapitalCities=db.collection("cities").whereEqualTo("capital",true);

Dart

finalcapitalcities=db.collection("cities").where("capital",isEqualTo:true);
Java
// Create a reference to the cities collectionCollectionReferencecities=db.collection("cities");// Create a query against the collection.Queryquery=cities.whereEqualTo("capital",true);// retrieve  query results asynchronously using query.get()ApiFuture<QuerySnapshot>querySnapshot=query.get();for(DocumentSnapshotdocument:querySnapshot.get().getDocuments()){System.out.println(document.getId());}
Python
cities_ref=db.collection("cities")query=cities_ref.where(filter=FieldFilter("capital","==",True))

Python

cities_ref=db.collection("cities")query=cities_ref.where(filter=FieldFilter("capital","==",True))
C++
Querycapital_cities=db->Collection("cities").WhereEqualTo("capital",FieldValue::Boolean(true));
Node.js
// Create a reference to the cities collectionconstcitiesRef=db.collection('cities');// Create a query against the collectionconstallCapitalsRes=citiesRef.where('capital','==',true);
Go
query:=client.Collection("cities").Where("capital","==",true)
PHP
$citiesRef = $db->collection('samples/php/cities');$query = $citiesRef->where('capital', '=', true);$snapshot = $query->documents();foreach ($snapshot as $document) {    printf('Document %s returned by query capital=true' . PHP_EOL, $document->id());}
Unity
CollectionReferencecitiesRef=db.Collection("cities");Queryquery=citiesRef.WhereEqualTo("Capital",true);query.GetSnapshotAsync().ContinueWithOnMainThread((querySnapshotTask)=>{foreach(DocumentSnapshotdocumentSnapshotinquerySnapshotTask.Result.Documents){Debug.Log(String.Format("Document {0} returned by query Capital=true",documentSnapshot.Id));}});
C#
CollectionReferencecitiesRef=db.Collection("cities");Queryquery=citiesRef.WhereEqualTo("Capital",true);QuerySnapshotquerySnapshot=awaitquery.GetSnapshotAsync();foreach(DocumentSnapshotdocumentSnapshotinquerySnapshot.Documents){Console.WriteLine("Document {0} returned by query Capital=true",documentSnapshot.Id);}
Ruby
cities_ref=firestore.colcollection_pathquery=cities_ref.where"capital","=",truequery.getdo|city|puts"Document#{city.document_id} returned by query capital=true."end

Execute a query

After creating a query object, use theget() function to retrieve the results:

Web

import{collection,query,where,getDocs}from"firebase/firestore";constq=query(collection(db,"cities"),where("capital","==",true));constquerySnapshot=awaitgetDocs(q);querySnapshot.forEach((doc)=>{// doc.data() is never undefined for query doc snapshotsconsole.log(doc.id," => ",doc.data());});

Web

Learn more about the tree-shakeable modular Web API and its advantages over the namespaced API.
db.collection("cities").where("capital","==",true).get().then((querySnapshot)=>{querySnapshot.forEach((doc)=>{// doc.data() is never undefined for query doc snapshotsconsole.log(doc.id," => ",doc.data());});}).catch((error)=>{console.log("Error getting documents: ",error);});
Swift
Note: This product is not available on watchOS and App Clip targets.
do{letquerySnapshot=tryawaitdb.collection("cities").whereField("capital",isEqualTo:true).getDocuments()fordocumentinquerySnapshot.documents{print("\(document.documentID) =>\(document.data())")}}catch{print("Error getting documents:\(error)")}
Objective-C
Note: This product is not available on watchOS and App Clip targets.
[[[self.dbcollectionWithPath:@"cities"]queryWhereField:@"capital"isEqualTo:@(YES)]getDocumentsWithCompletion:^(FIRQuerySnapshot*snapshot,NSError*error){if(error!=nil){NSLog(@"Error getting documents: %@",error);}else{for(FIRDocumentSnapshot*documentinsnapshot.documents){NSLog(@"%@ => %@",document.documentID,document.data);}}}];

Kotlin

db.collection("cities").whereEqualTo("capital",true).get().addOnSuccessListener{documents->for(documentindocuments){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(newOnCompleteListener<QuerySnapshot>(){@OverridepublicvoidonComplete(@NonNullTask<QuerySnapshot>task){if(task.isSuccessful()){for(QueryDocumentSnapshotdocument: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(vardocSnapshotinquerySnapshot.docs){print('${docSnapshot.id} =>${docSnapshot.data()}');}},onError:(e)=>print("Error completing:$e"),);
Java
// asynchronously retrieve multiple documentsApiFuture<QuerySnapshot>future=db.collection("cities").whereEqualTo("capital",true).get();// future.get() blocks on responseList<QueryDocumentSnapshot>documents=future.get().getDocuments();for(DocumentSnapshotdocument:documents){System.out.println(document.getId()+" => "+document.toObject(City.class));}
Python
# Note: Use of CollectionRef stream() is prefered to get()docs=(db.collection("cities").where(filter=FieldFilter("capital","==",True)).stream())fordocindocs:print(f"{doc.id} =>{doc.to_dict()}")

Python

# Note: Use of CollectionRef stream() is prefered to get()docs=(db.collection("cities").where(filter=FieldFilter("capital","==",True)).stream())asyncfordocindocs:print(f"{doc.id} =>{doc.to_dict()}")
C++
db->Collection("cities").WhereEqualTo("capital",FieldValue::Boolean(true)).Get().OnCompletion([](constFuture<QuerySnapshot>&future){if(future.error()==Error::kErrorOk){for(constDocumentSnapshot&document:future.result()->documents()){std::cout <<document <<std::endl;}}else{std::cout <<"Error getting documents: " <<future.error_message()                  <<std::endl;}});
Node.js
constcitiesRef=db.collection('cities');constsnapshot=awaitcitiesRef.where('capital','==',true).get();if(snapshot.empty){console.log('No matching documents.');return;}snapshot.forEach(doc=>{console.log(doc.id,'=>',doc.data());});
Go
import("context""fmt""cloud.google.com/go/firestore""google.golang.org/api/iterator")funcmultipleDocs(ctxcontext.Context,client*firestore.Client)error{fmt.Println("All capital cities:")iter:=client.Collection("cities").Where("capital","==",true).Documents(ctx)for{doc,err:=iter.Next()iferr==iterator.Done{break}iferr!=nil{returnerr}fmt.Println(doc.Data())}returnnil}
PHP

PHP

For more on installing and creating aCloud Firestore client, refer toCloud Firestore Client Libraries.

$citiesRef = $db->collection('samples/php/cities');$query = $citiesRef->where('capital', '=', true);$documents = $query->documents();foreach ($documents as $document) {    if ($document->exists()) {        printf('Document data for document %s:' . PHP_EOL, $document->id());        print_r($document->data());        printf(PHP_EOL);    } else {        printf('Document %s does not exist!' . PHP_EOL, $document->id());    }}
Unity
QuerycapitalQuery=db.Collection("cities").WhereEqualTo("Capital",true);capitalQuery.GetSnapshotAsync().ContinueWithOnMainThread(task=>{QuerySnapshotcapitalQuerySnapshot=task.Result;foreach(DocumentSnapshotdocumentSnapshotincapitalQuerySnapshot.Documents){Debug.Log(String.Format("Document data for {0} document:",documentSnapshot.Id));Dictionary<string,object>city=documentSnapshot.ToDictionary();foreach(KeyValuePair<string,object>pairincity){Debug.Log(String.Format("{0}: {1}",pair.Key,pair.Value));}// Newline to separate entriesDebug.Log("");};});
C#
QuerycapitalQuery=db.Collection("cities").WhereEqualTo("Capital",true);QuerySnapshotcapitalQuerySnapshot=awaitcapitalQuery.GetSnapshotAsync();foreach(DocumentSnapshotdocumentSnapshotincapitalQuerySnapshot.Documents){Console.WriteLine("Document data for {0} document:",documentSnapshot.Id);Dictionary<string,object>city=documentSnapshot.ToDictionary();foreach(KeyValuePair<string,object>pairincity){Console.WriteLine("{0}: {1}",pair.Key,pair.Value);}Console.WriteLine("");}
Ruby
cities_ref=firestore.colcollection_pathquery=cities_ref.where"capital","=",truequery.getdo|city|puts"#{city.document_id} data:#{city.data}."end

SeeGet Data for more information on retrieving query results. Youcan alsoadd a listener to a query to get the current results andlisten for future updates.

Query operators

Thewhere() method takes three parameters: a field to filter on, a comparisonoperator, and a value.Cloud Firestore supports the following comparisonoperators:

Note: For Apple, Android, and Java, the comparison operator is explicitly named inthe method.

For example:

Web

conststateQuery=query(citiesRef,where("state","==","CA"));constpopulationQuery=query(citiesRef,where("population","<",100000));constnameQuery=query(citiesRef,where("name",">=","San Francisco"));

Web

Learn more about the tree-shakeable modular Web API and its advantages over the namespaced API.
conststateQuery=citiesRef.where("state","==","CA");constpopulationQuery=citiesRef.where("population","<",100000);constnameQuery=citiesRef.where("name",">=","San Francisco");
Swift
Note: This product is not available on watchOS and App Clip targets.
letstateQuery=citiesRef.whereField("state",isEqualTo:"CA")letpopulationQuery=citiesRef.whereField("population",isLessThan:100000)letnameQuery=citiesRef.whereField("name",isGreaterThanOrEqualTo:"San Francisco")
Objective-C
Note: This product is not available on watchOS and App Clip targets.
FIRQuery*stateQuery=[citiesRefqueryWhereField:@"state"isEqualTo:@"CA"];FIRQuery*populationQuery=[citiesRefqueryWhereField:@"population"isLessThan:@100000];FIRQuery*nameQuery=[citiesRefqueryWhereField:@"name"isGreaterThanOrEqualTo:@"San Francisco"];

Kotlin

valstateQuery=citiesRef.whereEqualTo("state","CA")valpopulationQuery=citiesRef.whereLessThan("population",100000)valnameQuery=citiesRef.whereGreaterThanOrEqualTo("name","San Francisco")

Java

QuerystateQuery=citiesRef.whereEqualTo("state","CA");QuerypopulationQuery=citiesRef.whereLessThan("population",100000);QuerynameQuery=citiesRef.whereGreaterThanOrEqualTo("name","San Francisco");

Dart

finalcitiesRef=db.collection("cities");finalstateQuery=citiesRef.where("state",isEqualTo:"CA");finalpopulationQuery=citiesRef.where("population",isLessThan:100000);finalnameQuery=citiesRef.where("name",isEqualTo:"San Francisco");
Java
QuerystateQuery=cities.whereEqualTo("state","CA");QuerypopulationQuery=cities.whereLessThan("population",1000000L);QuerynameQuery=cities.whereGreaterThanOrEqualTo("name","San Francisco");
Python
cities_ref=db.collection("cities")cities_ref.where(filter=FieldFilter("state","==","CA"))cities_ref.where(filter=FieldFilter("population","<",1000000))cities_ref.where(filter=FieldFilter("name",">=","San Francisco"))

Python

cities_ref=db.collection("cities")cities_ref.where(filter=FieldFilter("state","==","CA"))cities_ref.where(filter=FieldFilter("population","<",1000000))cities_ref.where(filter=FieldFilter("name",">=","San Francisco"))
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
conststateQueryRes=awaitcitiesRef.where('state','==','CA').get();constpopulationQueryRes=awaitcitiesRef.where('population','<',1000000).get();constnameQueryRes=awaitcitiesRef.where('name','>=','San Francisco').get();
Go
countryQuery:=cities.Where("state","==","CA")popQuery:=cities.Where("population","<",1000000)cityQuery:=cities.Where("name",">=","San Francisco")
PHP
$stateQuery = $citiesRef->where('state', '=', 'CA');$populationQuery = $citiesRef->where('population', '>', 1000000);$nameQuery = $citiesRef->where('name', '>=', 'San Francisco');
Unity
QuerystateQuery=citiesRef.WhereEqualTo("State","CA");QuerypopulationQuery=citiesRef.WhereGreaterThan("Population",1000000);QuerynameQuery=citiesRef.WhereGreaterThanOrEqualTo("Name","San Francisco");
C#
CollectionReferencecitiesRef=db.Collection("cities");QuerystateQuery=citiesRef.WhereEqualTo("State","CA");QuerypopulationQuery=citiesRef.WhereGreaterThan("Population",1000000);QuerynameQuery=citiesRef.WhereGreaterThanOrEqualTo("Name","San Francisco");
Ruby
state_query=cities_ref.where"state","=","CA"population_query=cities_ref.where"population",">",1_000_000name_query=cities_ref.where"name",">=","San Francisco"

Not equal (!=)

Use the not equal (!=) operator to return documents where the given fieldexists and does not match the comparison value. For example:

Web

constnotCapitalQuery=query(citiesRef,where("capital","!=",false));

Web

Learn more about the tree-shakeable modular Web API and its advantages over the namespaced API.
citiesRef.where("capital","!=",false);
Swift
Note: This product is not available on watchOS and App Clip targets.
letnotEqualQuery=citiesRef.whereField("capital",isNotEqualTo:false)
Objective-C
Note: This product is not available on watchOS and App Clip targets.
query=[citiesRefqueryWhereField:@"capital"isNotEqualTo:@NO];

Kotlin

valnotCapitalQuery=citiesRef.whereNotEqualTo("capital",false)

Java

QuerynotCapitalQuery=citiesRef.whereNotEqualTo("capital",false);

Dart

finalcitiesRef=db.collection("cities");finalnotCapitals=citiesRef.where("capital",isNotEqualTo:true);
Java
CollectionReferencecitiesRef=db.collection("cities");Queryquery=citiesRef.whereNotEqualTo("capital",false);
Python
//Snippetnotyetavailable
C++
cities_ref.WhereNotEqualTo("capital",FieldValue::Boolean(false));
Node.js
constcapitalNotFalseRes=awaitcitiesRef.where('capital','!=',false).get();
Go
// Snippet not yet available
PHP
$stateQuery = $citiesRef->where('capital', '!=', false);
Unity
Queryquery=citiesRef.WhereNotEqualTo("capital",false);Queryquery=citiesRef.WhereNotEqualTo("capital",false);
C#
// Snippet not yet available
Ruby
cities_ref=firestore.colcollection_pathquery=cities_ref.where"capital","!=",false

This query returns everycity document where thecapital field exists with avalue other thanfalse ornull. This includescity documents where thecapital field value equalstrue or any non-boolean value besidesnull.

This query does not returncity documents where thecapital field does notexist.Not-equal (!=) andnot-in queries exclude documents where thegiven field does not exist.

A field exists when it's set to any value, including an empty string (""),null, andNaN (not a number). Note thatnull field values do notmatch!= clauses, becausex != null evaluates toundefined.

Warning: A!= query clause might match many documents in a collection. Tocontrol the number of results returned, use alimit clauseorpaginate your query.

Limitations

Note the following limitations for!= queries:

  • Only documents where the given field exists can match the query.
  • You can't combinenot-in and!= in a compound query.

Array membership

You can use thearray-contains operator to filter based on arrayvalues. For example:

Web

import{query,where}from"firebase/firestore";constq=query(citiesRef,where("regions","array-contains","west_coast"));

Web

Learn more about the tree-shakeable modular Web API and its advantages over the namespaced API.
citiesRef.where("regions","array-contains","west_coast");
Swift
Note: This product is not available on watchOS and App Clip targets.
citiesRef.whereField("regions",arrayContains:"west_coast")
Objective-C
Note: This product is not available on watchOS and App Clip targets.
[citiesRefqueryWhereField:@"state"arrayContains:@"west_coast"];

Kotlin

valcitiesRef=db.collection("cities")citiesRef.whereArrayContains("regions","west_coast")

Java

CollectionReferencecitiesRef=db.collection("cities");citiesRef.whereArrayContains("regions","west_coast");

Dart

finalcitiesRef=db.collection("cities");finalwestCoastcities=citiesRef.where("regions",arrayContains:"west_coast");
Java
CollectionReferencecitiesRef=db.collection("cities");QuerywestCoastQuery=citiesRef.whereArrayContains("regions","west_coast");
Python
cities_ref=db.collection("cities")query=cities_ref.where(filter=FieldFilter("regions","array_contains","west_coast"))

Python

cities_ref=db.collection("cities")query=cities_ref.where(filter=FieldFilter("regions","array_contains","west_coast"))
C++
CollectionReferencecities_ref=db->Collection("cities");cities_ref.WhereArrayContains("region",FieldValue::String("west_coast"));
Node.js
constwestCoastCities=citiesRef.where('regions','array-contains','west_coast').get();
Go
query:=cities.Where("regions","array-contains","west_coast").Documents(ctx)
PHP
$containsQuery = $citiesRef->where('regions', 'array-contains', 'west_coast');
Unity
CollectionReferencecitiesRef=db.Collection("cities");QueryarrayContainsQuery=citiesRef.WhereArrayContains("region","west_coast");
C#
CollectionReferencecitiesRef=db.Collection("cities");Queryquery=citiesRef.WhereArrayContains("Regions","west_coast");
Ruby
cities_ref=firestore.colcollection_pathcities=cities_ref.where"regions","array-contains","west_coast"

This query returns everycity document where theregions field is an array thatcontainswest_coast. If the array has multiple instances of the value youquery on, the document is included in the results only once.

You can use at most onearray-contains clause per disjunction (or group).You can't combinearray-contains witharray-contains-any in the samedisjunction.

in,not-in, andarray-contains-any

Use thein operator to combineup to 30equality (==) clauses on the same field with a logicalOR. Anin queryreturns documents where the given field matches any of the comparison values.For example:

Web

import{query,where}from"firebase/firestore";constq=query(citiesRef,where('country','in',['USA','Japan']));

Web

Learn more about the tree-shakeable modular Web API and its advantages over the namespaced API.
citiesRef.where('country','in',['USA','Japan']);
Swift
Note: This product is not available on watchOS and App Clip targets.
letcitiesRef=db.collection("cities")citiesRef.whereField("country",in:["USA","Japan"])
Objective-C
Note: This product is not available on watchOS and App Clip targets.
FIRCollectionReference*citiesRef=[self.dbcollectionWithPath:@"cities"];[citiesRefqueryWhereField:@"country"in:@[@"USA",@"Japan"]];

Kotlin

valcitiesRef=db.collection("cities")citiesRef.whereIn("country",listOf("USA","Japan"))

Java

CollectionReferencecitiesRef=db.collection("cities");citiesRef.whereIn("country",Arrays.asList("USA","Japan"));

Dart

finalcitiesRef=db.collection("cities");finalcities=citiesRef.where("country",whereIn:["USA","Japan"]);
Java
CollectionReferencecitiesRef=db.collection("cities");Queryquery=citiesRef.whereIn("country",Arrays.asList("USA","Japan"));
Python
cities_ref=db.collection("cities")query=cities_ref.where(filter=FieldFilter("country","in",["USA","Japan"]))returnquery

Python

cities_ref=db.collection("cities")query=cities_ref.where(filter=FieldFilter("country","in",["USA","Japan"]))returnquery
C++
CollectionReferencecities_ref=db->Collection("cities");cities_ref.WhereIn("country",std::vector<FieldValue>{FieldValue::String("USA"),FieldValue::String("Japan")});
Node.js
constusaOrJapan=awaitcitiesRef.where('country','in',['USA','Japan']).get();
Go
cities:=client.Collection("cities")query:=cities.Where("country","in",[]string{"USA","Japan"}).Documents(ctx)
PHP
$rangeQuery = $citiesRef->where('country', 'in', ['USA', 'Japan']);
Unity
CollectionReferencecitiesRef=db.Collection("cities");ListcountriesList=newList<object>(){"USA","Japan"};QuerywhereInQuery=citiesRef.WhereIn("country",countriesList);
C#
CollectionReferencecitiesRef=db.Collection("cities");Queryquery=citiesRef.WhereIn("Country",new[]{"USA","Japan"});
Ruby
cities_ref=firestore.colcollection_pathusr_or_japan=cities_ref.where"country","in",["USA","Japan"]

This query returns everycity document where thecountry field is settoUSA orJapan. From the example data, this includestheSF,LA,DC, andTOK documents.

not-in

Use thenot-in operator to combine up to 10 not equal (!=) clauses on thesame field with a logicalAND. Anot-in query returns documents where thegiven field exists, is notnull, and does not match any of thecomparison values. For example:

Web

import{query,where}from"firebase/firestore";constq=query(citiesRef,where('country','not-in',['USA','Japan']));

Web

Learn more about the tree-shakeable modular Web API and its advantages over the namespaced API.
citiesRef.where('country','not-in',['USA','Japan']);
Swift
Note: This product is not available on watchOS and App Clip targets.
citiesRef.whereField("country",notIn:["USA","Japan"])
Objective-C
Note: This product is not available on watchOS and App Clip targets.
[citiesRefqueryWhereField:@"country"notIn:@[@"USA",@"Japan"]];

Kotlin

citiesRef.whereNotIn("country",listOf("USA","Japan"))

Java

citiesRef.whereNotIn("country",Arrays.asList("USA","Japan"));

Dart

finalcitiesRef=db.collection("cities");finalcities=citiesRef.where("country",whereNotIn:["USA","Japan"]);
Java
CollectionReferencecitiesRef=db.collection("cities");Queryquery=citiesRef.whereNotIn("country",Arrays.asList("USA","Japan"));
Python
//Snippetnotyetavailable
C++
cities_ref.WhereNotIn("country",std::vector<FieldValue>{FieldValue::String("USA"),FieldValue::String("Japan")});
Node.js
constnotUsaOrJapan=awaitcitiesRef.where('country','not-in',['USA','Japan']).get();
Go
// Snippet not yet available
PHP
$stateQuery = $citiesRef->where(    'country',    \Google\Cloud\Firestore\V1\StructuredQuery\FieldFilter\Operator::NOT_IN,    ['USA', 'Japan']);
Unity
Queryquery=citiesRef.WhereNotIn(newFieldPath("country"),newList<string>{"USA","Japan"});Queryquery=citiesRef.WhereNotIn("country",newList<object>(){"USA","Japan"});
C#
// Snippet not yet available
Ruby
cities_ref=firestore.colcollection_pathusr_or_japan=cities_ref.where"country","not_in",["USA","Japan"]

This query returns everycity document where thecountry field exists and isnot set toUSA,Japan, ornull. From the example data, this includes theLondon andHong Kong documents.

not-in queries exclude documents where thegiven field does not exist. A field exists when it's set to any value,including an empty string (""),null, andNaN (not a number). Notethatx != null evaluates toundefined. Anot-in query withnull as one of the comparison values does not match any documents.

Warning: Anot-in query clause might match many documents in a collection. Tocontrol the number of results returned, use alimit clauseorpaginate your query.

array-contains-any

Use thearray-contains-any operator to combineup to 30array-contains clauses on the same field with a logicalOR. Anarray-contains-any query returns documents where the given field is an arraythat contains one or more of the comparison values:

Web

import{query,where}from"firebase/firestore";constq=query(citiesRef,where('regions','array-contains-any',['west_coast','east_coast']));

Web

Learn more about the tree-shakeable modular Web API and its advantages over the namespaced API.
citiesRef.where('regions','array-contains-any',['west_coast','east_coast']);
Swift
Note: This product is not available on watchOS and App Clip targets.
letcitiesRef=db.collection("cities")citiesRef.whereField("regions",arrayContainsAny:["west_coast","east_coast"])
Objective-C
Note: This product is not available on watchOS and App Clip targets.
FIRCollectionReference*citiesRef=[self.dbcollectionWithPath:@"cities"];[citiesRefqueryWhereField:@"regions"arrayContainsAny:@[@"west_coast",@"east_coast"]];

Kotlin

valcitiesRef=db.collection("cities")citiesRef.whereArrayContainsAny("regions",listOf("west_coast","east_coast"))

Java

CollectionReferencecitiesRef=db.collection("cities");citiesRef.whereArrayContainsAny("regions",Arrays.asList("west_coast","east_coast"));

Dart

finalcitiesRef=db.collection("cities");finalcities=citiesRef.where("regions",arrayContainsAny:["west_coast","east_coast"]);
Java
CollectionReferencecitiesRef=db.collection("cities");Queryquery=citiesRef.whereArrayContainsAny("regions",Arrays.asList("west_coast","east_coast"));
Python
cities_ref=db.collection("cities")query=cities_ref.where(filter=FieldFilter("regions","array_contains_any",["west_coast","east_coast"]))returnquery

Python

cities_ref=db.collection("cities")query=cities_ref.where(filter=FieldFilter("regions","array_contains_any",["west_coast","east_coast"]))returnquery
C++
CollectionReferencecities_ref=db->Collection("cities");cities_ref.WhereArrayContainsAny("region",std::vector<FieldValue>{FieldValue::String("west_coast"),FieldValue::String("east_coast")});
Node.js
constcoastalCities=awaitcitiesRef.where('regions','array-contains-any',['west_coast','east_coast']).get();
Go
cities:=client.Collection("cities")query:=cities.Where("regions","array-contains-any",[]string{"west_coast","east_coast"}).Documents(ctx)
PHP
$containsQuery = $citiesRef->where('regions', 'array-contains-any', ['west_coast', 'east_coast']);
Unity
Queryquery=citiesRef.WhereArrayContainsAny("regions",newList<object>(){newList<object>(){"west_coast"},newList<object>(){"east_coast"}});
C#
CollectionReferencecitiesRef=db.Collection("cities");Queryquery=citiesRef.WhereArrayContainsAny("Regions",new[]{"west_coast","east_coast"});
Ruby
cities_ref=firestore.colcollection_pathcostal_cities=cities_ref.where"regions","array-contains-any",["west_coast","east_coast"]

This query returns every city document where theregions field is an arraythat containswest_coast oreast_coast. From the example data, this includestheSF,LA, andDC documents.

Results fromarray-contains-any are de-duped. Even if a document's array fieldmatches more than one of the comparison values, the result set includes thatdocument only once.

array-contains-any always filters by the array data type. For example, thequery above would not return a city document where instead of an array, theregions field is the stringwest_coast.

You can use an array value as a comparison value forin, but unlikearray-contains-any, the clause matches for an exact match of array length,order, and values. For example:

Web

import{query,where}from"firebase/firestore";constq=query(citiesRef,where('regions','in',[['west_coast'],['east_coast']]));

Web

Learn more about the tree-shakeable modular Web API and its advantages over the namespaced API.
citiesRef.where('regions','in',[['west_coast'],['east_coast']]);
Swift
Note: This product is not available on watchOS and App Clip targets.
citiesRef.whereField("regions",in:[["west_coast"],["east_coast"]])
Objective-C
Note: This product is not available on watchOS and App Clip targets.
[citiesRefqueryWhereField:@"regions"in:@[@[@"west_coast"],@[@"east_coast"]]];

Kotlin

citiesRef.whereIn("regions",listOf(arrayOf("west_coast"),arrayOf("east_coast")))

Java

citiesRef.whereIn("regions",Arrays.asList(newString[]{"west_coast"},newString[]{"east_coast"}));

Dart

finalcitiesRef=db.collection("cities");finalcities=citiesRef.where("regions",whereIn:[["west_coast"],["east_coast"]]);
Java
CollectionReferencecitiesRef=db.collection("cities");Queryquery=citiesRef.whereIn("regions",Arrays.asList(Arrays.asList("west_coast"),Arrays.asList("east_coast")));
Python
cities_ref=db.collection("cities")query=cities_ref.where(filter=FieldFilter("regions","in",[["west_coast"],["east_coast"]]))returnquery

Python

cities_ref=db.collection("cities")query=cities_ref.where(filter=FieldFilter("regions","in",[["west_coast"],["east_coast"]]))returnquery
C++
cities_ref.WhereIn("region",std::vector<FieldValue>{FieldValue::String("west_coast"),FieldValue::String("east_coast")});
Node.js
constexactlyOneCoast=awaitcitiesRef.where('regions','in',[['west_coast','east_coast']]).get();
Go
cities:=client.Collection("cities")query:=cities.Where("regions","in",[][]string{{"west_coast"}, {"east_coast"}}).Documents(ctx)
PHP
$rangeQuery = $citiesRef->where('regions', 'in', [['west_coast'], ['east_coast']]);
Unity
Queryquery=citiesRef.WhereIn(newFieldPath("regions"),newList<string>{"west_coast","east_coast"});
C#
CollectionReferencecitiesRef=db.Collection("cities");Queryquery=citiesRef.WhereIn("Regions",new[]{new[]{"west_coast"},new[]{"east_coast"}});
Ruby
cities_ref=firestore.colcollection_pathexactly_one_cost=cities_ref.where"regions","in",[["west_coast"],["east_coast"]]

This query returns every city document where theregions field is an arraythat contains exactly one element of eitherwest_coast oreast_coast.From the example data, only theDC document qualifies with itsregions fieldof["east_coast"]. TheSF document, however, doesnot match because itsregions field is["west_coast", "norcal"].

Limitations

Note the following limitations forin,not-in, andarray-contains-any:

  • Cloud Firestore provides support for logicalOR queriesthrough theor,in, andarray-contains-any operators. These queriesare limited to30 disjunctions based on the query's disjunctive normal form.This limit is fixed and cannot be adjusted.
  • You can use at most onearray-contains clause per disjunction (or group).You can't combinearray-contains witharray-contains-any in the samedisjunction.
  • You can't combinenot-in with not equals!=.
  • not-in supports up to 10 comparison values.

Compound (AND) queries

You can combine constraints with a logicalAND by chaining multiple equalityoperators (== orarray-contains). However, you must create acomposite index to combine equality operators with the inequalityoperators,<,<=,>, and!=.

Web

import{query,where}from"firebase/firestore";constq1=query(citiesRef,where("state","==","CO"),where("name","==","Denver"));constq2=query(citiesRef,where("state","==","CA"),where("population","<",1000000));

Web

Learn more about the tree-shakeable modular Web API and its advantages over the namespaced API.
constq1=citiesRef.where("state","==","CO").where("name","==","Denver");constq2=citiesRef.where("state","==","CA").where("population","<",1000000);
Swift
Note: This product is not available on watchOS and App Clip targets.
citiesRef.whereField("state",isEqualTo:"CO").whereField("name",isEqualTo:"Denver")citiesRef.whereField("state",isEqualTo:"CA").whereField("population",isLessThan:1000000)
Objective-C
Note: This product is not available on watchOS and App Clip targets.
[[citiesRefqueryWhereField:@"state"isEqualTo:@"CO"]queryWhereField:@"name"isGreaterThanOrEqualTo:@"Denver"];[[citiesRefqueryWhereField:@"state"isEqualTo:@"CA"]queryWhereField:@"population"isLessThan:@1000000];

Kotlin

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

finalcitiesRef=db.collection("cities");citiesRef.where("state",isEqualTo:"CO").where("name",isEqualTo:"Denver");citiesRef.where("state",isEqualTo:"CA").where("population",isLessThan:1000000);
Java
QuerychainedQuery1=cities.whereEqualTo("state","CO").whereEqualTo("name","Denver");
Python
cities_ref=db.collection("cities")denver_query=cities_ref.where(filter=FieldFilter("state","==","CO")).where(filter=FieldFilter("name","==","Denver"))large_us_cities_query=cities_ref.where(filter=FieldFilter("state","==","CA")).where(filter=FieldFilter("population",">",1000000))

Python

cities_ref=db.collection("cities")denver_query=cities_ref.where(filter=FieldFilter("state","==","CO")).where(filter=FieldFilter("name","==","Denver"))large_us_cities_query=cities_ref.where(filter=FieldFilter("state","==","CA")).where(filter=FieldFilter("population",">",1000000))
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
citiesRef.where('state','==','CO').where('name','==','Denver');citiesRef.where('state','==','CA').where('population','<',1000000);
Go
denverQuery:=cities.Where("name","==","Denver").Where("state","==","CO")caliQuery:=cities.Where("state","==","CA").Where("population","<=",1000000)query:=cities.Where("country","==","USA").Where("population",">",5000000)
PHP
$chainedQuery = $citiesRef    ->where('state', '=', 'CA')    ->where('name', '=', 'San Francisco');
Unity
QuerychainedQuery=citiesRef.WhereEqualTo("State","CA").WhereEqualTo("Name","San Francisco");
C#
CollectionReferencecitiesRef=db.Collection("cities");QuerychainedQuery=citiesRef.WhereEqualTo("State","CA").WhereEqualTo("Name","San Francisco");
Ruby
chained_query=cities_ref.where("state","=","CA").where("name","=","San Francisco")

OR queries

You can combine constraints with a logicalOR. For example:

Web

constq=query(citiesRef,or(where('capital','==',true),where('population','>=',1000000)));

Web

Not available.

Swift
letquery=db.collection("cities").whereFilter(Filter.orFilter([Filter.whereField("capital",isEqualTo:true),Filter.whereField("population",isGreaterThanOrEqualTo:1000000);]))
Objective-C
FIRCollectionReference*collection=[self.dbcollectionWithPath:@"cities"];FIRQuery*query=[collectionqueryWhereFilter:[FIRFilterorFilterWithFilters:@[[FIRFilterfilterWhereField:@"capital"isEqualTo:@YES],[FIRFilterfilterWhereField:@"population"isGreaterThanOrEqualTo:@1000000]]]];

Kotlin

valquery=collection.where(Filter.or(Filter.equalTo("capital",true),Filter.greaterThanOrEqualTo("population",1000000)))

Java

Queryquery=collection.where(Filter.or(Filter.equalTo("capital",true),Filter.greaterThanOrEqualTo("population",1000000)));

Dart

varquery=db.collection("cities").where(Filter.or(Filter("capital",isEqualTo:true),Filter("population",isGreaterThan:1000000),),);
Java

Snippet not available.

Python
fromgoogle.cloud.firestore_v1.base_queryimportFieldFilter,Orcol_ref=client.collection("cities")# Execute the queryquery=col_ref.where(filter=Or([FieldFilter("capital","==",True),FieldFilter("population",">",1_000_000),]))docs=query.stream()

Python

Snippet not available.

C++

Snippet not available.

Node.js
constbigCities=awaitcitiesRef.where(Filter.or(Filter.where('capital','==',true),Filter.where('population','>=',1000000))).get();
Go
import("context""fmt""io"firestore"cloud.google.com/go/firestore""google.golang.org/api/iterator")funcqueryFilterOr(wio.Writer,projectIdstring)error{// Instantiate a clientctx:=context.Background()client,err:=firestore.NewClient(ctx,projectId)iferr!=nil{returnerr}// always be sure to close the client to release resourcesdeferclient.Close()q1:=firestore.PropertyFilter{Path:"birthYear",Operator:"==",Value:1906,}q2:=firestore.PropertyFilter{Path:"birthYear",Operator:"==",Value:1815,}orFilter:=firestore.OrFilter{Filters:[]firestore.EntityFilter{q1,q2},}orQuery:=client.Collection("users").WhereEntity(orFilter)it:=orQuery.Documents(ctx)iferr!=nil{returnerr}fmt.Fprint(w,"Individual documents:\n")for{doc,err:=it.Next()iferr==iterator.Done{break}iferr!=nil{returnfmt.Errorf("documents iterator: %w",err)}fmt.Fprintf(w,"%s: %s",doc.Ref.ID,doc.Data()["birthYear"])}returnnil}
PHP

Snippet not available.

Unity
Queryquery=citiesRef.Where(Filter.Or(Filter.EqualTo("State","CA"),Filter.GreaterThanOrEqualTo("population",1000000)));query.GetSnapshotAsync().ContinueWithOnMainThread((querySnapshotTask)=>{foreach(DocumentSnapshotdocumentSnapshotinquerySnapshotTask.Result.Documents){Debug.Log(String.Format("Document {0} returned by query State=CA or population >= {1}",documentSnapshot.Id,1000000));}});
C#

Snippet not available.

Ruby

Snippet not available.

Cloud Firestore uses your composite indexes to serveOR queries. Ifyour indexes do not support the query,Cloud Firestoresuggests additional indexes for your database.

You can combineOR queries with compound queries to filter on combinationsofOR andAND operations. For example:

Web

constq=query(collection(db,"cities"),and(where('state','==','CA'),or(where('capital','==',true),where('population','>=',1000000))));

Web

Not available.

Swift
Note: This product is not available on watchOS and App Clip targets.
letquery=db.collection("cities").whereFilter(Filter.andFilter([Filter.whereField("state",isEqualTo:"CA"),Filter.orFilter([Filter.whereField("capital",isEqualTo:true),Filter.whereField("population",isGreaterThanOrEqualTo:1000000)])]))
Objective-C
Note: This product is not available on watchOS and App Clip targets.
FIRCollectionReference*collection=[self.dbcollectionWithPath:@"cities"];FIRQuery*query=[collectionqueryWhereFilter:[FIRFilterandFilterWithFilters:@[[FIRFilterfilterWhereField:@"state"isEqualTo:@"CA"],[FIRFilterorFilterWithFilters:@[[FIRFilterfilterWhereField:@"capital"isEqualTo:@YES],[FIRFilterfilterWhereField:@"population"isGreaterThanOrEqualTo:@1000000]]]]]];

Kotlin

valquery=collection.where(Filter.and(Filter.equalTo("state","CA"),Filter.or(Filter.equalTo("capital",true),Filter.greaterThanOrEqualTo("population",1000000))))

Java

Queryquery=collection.where(Filter.and(Filter.equalTo("state","CA"),Filter.or(Filter.equalTo("capital",true),Filter.greaterThanOrEqualTo("population",1000000))));

Dart

varquery=db.collection("cities").where(Filter.and(Filter("state",isEqualTo:"CA"),Filter.or(Filter("capital",isEqualTo:true),Filter("population",isGreaterThan:1000000),),),);
Java

Snippet not available.

Python

Snippet not available.

Python

Snippet not available.

C++

Snippet not available.

Node.js
constbigCitiesInCalifornia=awaitcitiesRef.where('state','==','CA').where(Filter.or(Filter.where('capital','==',true),Filter.where('population','>=',1000000))).get();
Go

Snippet not available.

PHP

Snippet not available.

Unity
Queryquery=citiesRef.Where(Filter.And(Filter.EqualTo("state","CA"),Filter.Or(Filter.EqualTo("capital",true),Filter.GreaterThanOrEqualTo("population",1000000))));
C#

Snippet not available.

Ruby

Snippet not available.

Limitations

Note the following limitations foror queries:

For a full description of limitations, seeQuery limitations.

Collection group queries

A collection group consists of all collections with the same ID. By default,queries retrieve results from a single collection in your database. Use acollection group query to retrieve documents from a collection group instead offrom a single collection.

For example, you can create alandmarks collection group by adding a landmarkssubcollection to each city:

Web

import{collection,addDoc}from"firebase/firestore";constcitiesRef=collection(db,'cities');awaitPromise.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

Learn more about the tree-shakeable modular Web API and its advantages over the namespaced API.
varcitiesRef=db.collection('cities');varlandmarks=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'})]);
Swift
Note: This product is not available on watchOS and App Clip targets.
letcitiesRef=db.collection("cities")vardata=["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)
Objective-C
Note: This product is not available on watchOS and App Clip targets.
FIRCollectionReference*citiesRef=[self.dbcollectionWithPath:@"cities"];NSDictionary*data=@{@"name":@"Golden Gate Bridge",@"type":@"bridge"};[[[citiesRefdocumentWithPath:@"SF"]collectionWithPath:@"landmarks"]addDocumentWithData:data];data=@{@"name":@"Legion of Honor",@"type":@"museum"};[[[citiesRefdocumentWithPath:@"SF"]collectionWithPath:@"landmarks"]addDocumentWithData:data];data=@{@"name":@"Griffith Park",@"type":@"park"};[[[citiesRefdocumentWithPath:@"LA"]collectionWithPath:@"landmarks"]addDocumentWithData:data];data=@{@"name":@"The Getty",@"type":@"museum"};[[[citiesRefdocumentWithPath:@"LA"]collectionWithPath:@"landmarks"]addDocumentWithData:data];data=@{@"name":@"Lincoln Memorial",@"type":@"memorial"};[[[citiesRefdocumentWithPath:@"DC"]collectionWithPath:@"landmarks"]addDocumentWithData:data];data=@{@"name":@"National Air and Space Museum",@"type":@"museum"};[[[citiesRefdocumentWithPath:@"DC"]collectionWithPath:@"landmarks"]addDocumentWithData:data];data=@{@"name":@"Ueno Park",@"type":@"park"};[[[citiesRefdocumentWithPath:@"TOK"]collectionWithPath:@"landmarks"]addDocumentWithData:data];data=@{@"name":@"National Museum of Nature and Science",@"type":@"museum"};[[[citiesRefdocumentWithPath:@"TOK"]collectionWithPath:@"landmarks"]addDocumentWithData:data];data=@{@"name":@"Jingshan Park",@"type":@"park"};[[[citiesRefdocumentWithPath:@"BJ"]collectionWithPath:@"landmarks"]addDocumentWithData:data];data=@{@"name":@"Beijing Ancient Observatory",@"type":@"museum"};[[[citiesRefdocumentWithPath:@"BJ"]collectionWithPath:@"landmarks"]addDocumentWithData:data];

Kotlin

valcitiesRef=db.collection("cities")valggbData=mapOf("name"to"Golden Gate Bridge","type"to"bridge",)citiesRef.document("SF").collection("landmarks").add(ggbData)vallohData=mapOf("name"to"Legion of Honor","type"to"museum",)citiesRef.document("SF").collection("landmarks").add(lohData)valgpData=mapOf("name"to"Griffth Park","type"to"park",)citiesRef.document("LA").collection("landmarks").add(gpData)valtgData=mapOf("name"to"The Getty","type"to"museum",)citiesRef.document("LA").collection("landmarks").add(tgData)vallmData=mapOf("name"to"Lincoln Memorial","type"to"memorial",)citiesRef.document("DC").collection("landmarks").add(lmData)valnasaData=mapOf("name"to"National Air and Space Museum","type"to"museum",)citiesRef.document("DC").collection("landmarks").add(nasaData)valupData=mapOf("name"to"Ueno Park","type"to"park",)citiesRef.document("TOK").collection("landmarks").add(upData)valnmData=mapOf("name"to"National Musuem of Nature and Science","type"to"museum",)citiesRef.document("TOK").collection("landmarks").add(nmData)valjpData=mapOf("name"to"Jingshan Park","type"to"park",)citiesRef.document("BJ").collection("landmarks").add(jpData)valbaoData=mapOf("name"to"Beijing Ancient Observatory","type"to"musuem",)citiesRef.document("BJ").collection("landmarks").add(baoData)

Java

CollectionReferencecitiesRef=db.collection("cities");Map<String,Object>ggbData=newHashMap<>();ggbData.put("name","Golden Gate Bridge");ggbData.put("type","bridge");citiesRef.document("SF").collection("landmarks").add(ggbData);Map<String,Object>lohData=newHashMap<>();lohData.put("name","Legion of Honor");lohData.put("type","museum");citiesRef.document("SF").collection("landmarks").add(lohData);Map<String,Object>gpData=newHashMap<>();gpData.put("name","Griffith Park");gpData.put("type","park");citiesRef.document("LA").collection("landmarks").add(gpData);Map<String,Object>tgData=newHashMap<>();tgData.put("name","The Getty");tgData.put("type","museum");citiesRef.document("LA").collection("landmarks").add(tgData);Map<String,Object>lmData=newHashMap<>();lmData.put("name","Lincoln Memorial");lmData.put("type","memorial");citiesRef.document("DC").collection("landmarks").add(lmData);Map<String,Object>nasaData=newHashMap<>();nasaData.put("name","National Air and Space Museum");nasaData.put("type","museum");citiesRef.document("DC").collection("landmarks").add(nasaData);Map<String,Object>upData=newHashMap<>();upData.put("name","Ueno Park");upData.put("type","park");citiesRef.document("TOK").collection("landmarks").add(upData);Map<String,Object>nmData=newHashMap<>();nmData.put("name","National Museum of Nature and Science");nmData.put("type","museum");citiesRef.document("TOK").collection("landmarks").add(nmData);Map<String,Object>jpData=newHashMap<>();jpData.put("name","Jingshan Park");jpData.put("type","park");citiesRef.document("BJ").collection("landmarks").add(jpData);Map<String,Object>baoData=newHashMap<>();baoData.put("name","Beijing Ancient Observatory");baoData.put("type","museum");citiesRef.document("BJ").collection("landmarks").add(baoData);

Dart

finalcitiesRef=db.collection("cities");finalggbData={"name":"Golden Gate Bridge","type":"bridge"};citiesRef.doc("SF").collection("landmarks").add(ggbData);finallohData={"name":"Legion of Honor","type":"museum"};citiesRef.doc("SF").collection("landmarks").add(lohData);finalgpData={"name":"Griffth Park","type":"park"};citiesRef.doc("LA").collection("landmarks").add(gpData);finaltgData={"name":"The Getty","type":"museum"};citiesRef.doc("LA").collection("landmarks").add(tgData);finallmData={"name":"Lincoln Memorial","type":"memorial"};citiesRef.doc("DC").collection("landmarks").add(lmData);finalnasaData={"name":"National Air and Space Museum","type":"museum"};citiesRef.doc("DC").collection("landmarks").add(nasaData);finalupData={"name":"Ueno Park","type":"park"};citiesRef.doc("TOK").collection("landmarks").add(upData);finalnmData={"name":"National Musuem of Nature and Science","type":"museum"};citiesRef.doc("TOK").collection("landmarks").add(nmData);finaljpData={"name":"Jingshan Park","type":"park"};citiesRef.doc("BJ").collection("landmarks").add(jpData);finalbaoData={"name":"Beijing Ancient Observatory","type":"musuem"};citiesRef.doc("BJ").collection("landmarks").add(baoData);
Java
CollectionReferencecities=db.collection("cities");finalList<ApiFuture<WriteResult>>futures=Arrays.asList(cities.document("SF").collection("landmarks").document().set(newHashMap<String,String>(){{put("name","Golden Gate Bridge");put("type","bridge");}}),cities.document("SF").collection("landmarks").document().set(newHashMap<String,String>(){{put("name","Legion of Honor");put("type","museum");}}),cities.document("LA").collection("landmarks").document().set(newHashMap<String,String>(){{put("name","Griffith Park");put("type","park");}}),cities.document("LA").collection("landmarks").document().set(newHashMap<String,String>(){{put("name","The Getty");put("type","museum");}}),cities.document("DC").collection("landmarks").document().set(newHashMap<String,String>(){{put("name","Lincoln Memorial");put("type","memorial");}}),cities.document("DC").collection("landmarks").document().set(newHashMap<String,String>(){{put("name","National Air and Space Museum");put("type","museum");}}),cities.document("TOK").collection("landmarks").document().set(newHashMap<String,String>(){{put("name","Ueno Park");put("type","park");}}),cities.document("TOK").collection("landmarks").document().set(newHashMap<String,String>(){{put("name","National Museum of Nature and Science");put("type","museum");}}),cities.document("BJ").collection("landmarks").document().set(newHashMap<String,String>(){{put("name","Jingshan Park");put("type","park");}}),cities.document("BJ").collection("landmarks").document().set(newHashMap<String,String>(){{put("name","Beijing Ancient Observatory");put("type","museum");}}));finalList<WriteResult>landmarks=ApiFutures.allAsList(futures).get();
Python
cities=db.collection("cities")sf_landmarks=cities.document("SF").collection("landmarks")sf_landmarks.document().set({"name":"Golden Gate Bridge","type":"bridge"})sf_landmarks.document().set({"name":"Legion of Honor","type":"museum"})la_landmarks=cities.document("LA").collection("landmarks")la_landmarks.document().set({"name":"Griffith Park","type":"park"})la_landmarks.document().set({"name":"The Getty","type":"museum"})dc_landmarks=cities.document("DC").collection("landmarks")dc_landmarks.document().set({"name":"Lincoln Memorial","type":"memorial"})dc_landmarks.document().set({"name":"National Air and Space Museum","type":"museum"})tok_landmarks=cities.document("TOK").collection("landmarks")tok_landmarks.document().set({"name":"Ueno Park","type":"park"})tok_landmarks.document().set({"name":"National Museum of Nature and Science","type":"museum"})bj_landmarks=cities.document("BJ").collection("landmarks")bj_landmarks.document().set({"name":"Jingshan Park","type":"park"})bj_landmarks.document().set({"name":"Beijing Ancient Observatory","type":"museum"})

Python

cities=db.collection("cities")sf_landmarks=cities.document("SF").collection("landmarks")awaitsf_landmarks.document().set({"name":"Golden Gate Bridge","type":"bridge"})awaitsf_landmarks.document().set({"name":"Legion of Honor","type":"museum"})la_landmarks=cities.document("LA").collection("landmarks")awaitla_landmarks.document().set({"name":"Griffith Park","type":"park"})awaitla_landmarks.document().set({"name":"The Getty","type":"museum"})dc_landmarks=cities.document("DC").collection("landmarks")awaitdc_landmarks.document().set({"name":"Lincoln Memorial","type":"memorial"})awaitdc_landmarks.document().set({"name":"National Air and Space Museum","type":"museum"})tok_landmarks=cities.document("TOK").collection("landmarks")awaittok_landmarks.document().set({"name":"Ueno Park","type":"park"})awaittok_landmarks.document().set({"name":"National Museum of Nature and Science","type":"museum"})bj_landmarks=cities.document("BJ").collection("landmarks")awaitbj_landmarks.document().set({"name":"Jingshan Park","type":"park"})awaitbj_landmarks.document().set({"name":"Beijing Ancient Observatory","type":"museum"})
C++
// Get a new write batchWriteBatchbatch=db->batch();DocumentReferencesf_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")}});DocumentReferencela_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")}});DocumentReferencedc_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")}});DocumentReferencetok_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")}});DocumentReferencebj_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 batchbatch.Commit().OnCompletion([](constFuture<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
constcitiesRef=db.collection('cities');awaitcitiesRef.doc('SF').collection('landmarks').doc().set({name:'Golden Gate Bridge',type:'bridge'});awaitcitiesRef.doc('SF').collection('landmarks').doc().set({name:'Legion of Honor',type:'museum'});awaitcitiesRef.doc('LA').collection('landmarks').doc().set({name:'Griffith Park',type:'park'});awaitcitiesRef.doc('LA').collection('landmarks').doc().set({name:'The Getty',type:'museum'});awaitcitiesRef.doc('DC').collection('landmarks').doc().set({name:'Lincoln Memorial',type:'memorial'});awaitcitiesRef.doc('DC').collection('landmarks').doc().set({name:'National Air and Space Museum',type:'museum'});awaitcitiesRef.doc('TOK').collection('landmarks').doc().set({name:'Ueno Park',type:'park'});awaitcitiesRef.doc('TOK').collection('landmarks').doc().set({name:'National Museum of Nature and Science',type:'museum'});awaitcitiesRef.doc('BJ').collection('landmarks').doc().set({name:'Jingshan Park',type:'park'});awaitcitiesRef.doc('BJ').collection('landmarks').doc().set({name:'Beijing Ancient Observatory',type:'museum'});
Go
import("context""fmt""cloud.google.com/go/firestore")// collectionGroupSetup sets up a collection group to query.funccollectionGroupSetup(projectID,cityCollectionstring)error{ctx:=context.Background()client,err:=firestore.NewClient(ctx,projectID)iferr!=nil{returnfmt.Errorf("firestore.NewClient: %w",err)}deferclient.Close()landmarks:=[]struct{city,name,tstring}{{"SF","Golden Gate Bridge","bridge"},{"SF","Legion of Honor","museum"},{"LA","Griffith Park","park"},{"LA","The Getty","museum"},{"DC","Lincoln Memorial","memorial"},{"DC","National Air and Space Museum","museum"},{"TOK","Ueno Park","park"},{"TOK","National Museum of Nature and Science","museum"},{"BJ","Jingshan Park","park"},{"BJ","Beijing Ancient Observatory","museum"},}cities:=client.Collection(cityCollection)for_,l:=rangelandmarks{if_,err:=cities.Doc(l.city).Collection("landmarks").NewDoc().Set(ctx,map[string]string{"name":l.name,"type":l.t,});err!=nil{returnfmt.Errorf("Set: %w",err)}}returnnil}
PHP
$citiesRef = $db->collection('samples/php/cities');$citiesRef->document('SF')->collection('landmarks')->newDocument()->set([    'name' => 'Golden Gate Bridge',    'type' => 'bridge']);$citiesRef->document('SF')->collection('landmarks')->newDocument()->set([    'name' => 'Legion of Honor',    'type' => 'museum']);$citiesRef->document('LA')->collection('landmarks')->newDocument()->set([    'name' => 'Griffith Park',    'type' => 'park']);$citiesRef->document('LA')->collection('landmarks')->newDocument()->set([    'name' => 'The Getty',    'type' => 'museum']);$citiesRef->document('DC')->collection('landmarks')->newDocument()->set([    'name' => 'Lincoln Memorial',    'type' => 'memorial']);$citiesRef->document('DC')->collection('landmarks')->newDocument()->set([    'name' => 'National Air and Space Museum',    'type' => 'museum']);$citiesRef->document('TOK')->collection('landmarks')->newDocument()->set([    'name' => 'Ueno Park',    'type' => 'park']);$citiesRef->document('TOK')->collection('landmarks')->newDocument()->set([    'name' => 'National Museum of Nature and Science',    'type' => 'museum']);$citiesRef->document('BJ')->collection('landmarks')->newDocument()->set([    'name' => 'Jingshan Park',    'type' => 'park']);$citiesRef->document('BJ')->collection('landmarks')->newDocument()->set([    'name' => 'Beijing Ancient Observatory',    'type' => 'museum']);print('Added example landmarks collections to the cities collection.' . PHP_EOL);
Unity
List<Task<DocumentReference>>futures=newList<Task<DocumentReference>>(){citiesRef.Document("SF").Collection("landmarks").AddAsync(newDictionary<string,object>(){{"name","Golden Gate Bridge"},{"type","bridge"},}),citiesRef.Document("SF").Collection("landmarks").AddAsync(newDictionary<string,object>(){{"name","Legion of Honor"},{"type","museum"},}),citiesRef.Document("LA").Collection("landmarks").AddAsync(newDictionary<string,object>(){{"name","Griffith Park"},{"type","park"},}),citiesRef.Document("LA").Collection("landmarks").AddAsync(newDictionary<string,object>(){{"name","The Getty"},{"type","museum"},}),citiesRef.Document("DC").Collection("landmarks").AddAsync(newDictionary<string,object>(){{"name","Lincoln Memorial"},{"type","memorial"},}),citiesRef.Document("DC").Collection("landmarks").AddAsync(newDictionary<string,object>(){{"name","National Air and Space Museum"},{"type","museum"},}),citiesRef.Document("TOK").Collection("landmarks").AddAsync(newDictionary<string,object>(){{"name","Ueno Park"},{"type","park"},}),citiesRef.Document("TOK").Collection("landmarks").AddAsync(newDictionary<string,object>(){{"name","National Museum of Nature and Science"},{"type","museum"},}),citiesRef.Document("BJ").Collection("landmarks").AddAsync(newDictionary<string,object>(){{"name","Jingshan Park"},{"type","park"},}),citiesRef.Document("BJ").Collection("landmarks").AddAsync(newDictionary<string,object>(){{"name","Beijing Ancient Observatory"},{"type","museum"},})};DocumentReference[]landmarks=Task.WhenAll(futures).Result;
C#
// Copyright(c) 2017 Google Inc.//// Licensed under the Apache License, Version 2.0 (the "License"); you may not// use this file except in compliance with the License. You may obtain a copy of// the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the// License for the specific language governing permissions and limitations under// the License.usingGoogle.Cloud.Firestore;usingGoogle.Cloud.Firestore.Admin.V1;usingGoogle.Protobuf.WellKnownTypes;usingGrpc.Core;usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.Threading.Tasks;usingstaticGoogle.Cloud.Firestore.Admin.V1.Index.Types;namespaceGoogleCloudSamples{publicclassQueryData{publicstaticstringUsage=@"Usage:C:\> dotnet run command YOUR_PROJECT_IDWhere command is one of    query-create-examples    create-query-state    create-query-capital    simple-queries    array-contains-query    array-contains-any-query    in-query    in-query-array    collection-group-query    subcollection-query    chained-query    composite-index-chained-query    range-query    multiple-inequalities";privatestaticasyncTaskQueryCreateExamples(stringproject){FirestoreDbdb=FirestoreDb.Create(project);// Note: the extra braces here are just to allow multiple citiesRef local variables.{CollectionReferencecitiesRef=db.Collection("cities");awaitcitiesRef.Document("SF").SetAsync(newDictionary<string,object>{{"Name","San Francisco"},{"State","CA"},{"Country","USA"},{"Capital",false},{"Population",860000},{"Density",18000},{"Regions",new[]{"west_coast","norcal"}}});awaitcitiesRef.Document("LA").SetAsync(newDictionary<string,object>{{"Name","Los Angeles"},{"State","CA"},{"Country","USA"},{"Capital",false},{"Population",3900000},{"Density",8300},{"Regions",new[]{"west_coast","socal"}}});awaitcitiesRef.Document("DC").SetAsync(newDictionary<string,object>{{"Name","Washington D.C."},{"State",null},{"Country","USA"},{"Capital",true},{"Population",680000},{"Density",11300},{"Regions",new[]{"east_coast"}}});awaitcitiesRef.Document("TOK").SetAsync(newDictionary<string,object>{{"Name","Tokyo"},{"State",null},{"Country","Japan"},{"Capital",true},{"Population",9000000},{"Density",16000},{"Regions",new[]{"kanto","honshu"}}});awaitcitiesRef.Document("BJ").SetAsync(newDictionary<string,object>{{"Name","Beijing"},{"State",null},{"Country","China"},{"Capital",true},{"Population",21500000},{"Density",3500},{"Regions",new[]{"jingjinji","hebei"}}});Console.WriteLine("Added example cities data to the cities collection.");}{CollectionReferencecitiesRef=db.Collection("cities");awaitcitiesRef.Document("SF").Collection("landmarks").Document().SetAsync(new{Name="Golden Gate Bridge",Type="bridge"});awaitcitiesRef.Document("SF").Collection("landmarks").Document().SetAsync(new{Name="Legion of Honor",Type="museum"});awaitcitiesRef.Document("LA").Collection("landmarks").Document().SetAsync(new{Name="Griffith Park",Type="park"});awaitcitiesRef.Document("DC").Collection("landmarks").Document().SetAsync(new{Name="Lincoln Memorial",Type="memorial"});awaitcitiesRef.Document("DC").Collection("landmarks").Document().SetAsync(new{Name="National Air And Space Museum",Type="museum"});awaitcitiesRef.Document("TOK").Collection("landmarks").Document().SetAsync(new{Name="Ueno Park",Type="park"});awaitcitiesRef.Document("TOK").Collection("landmarks").Document().SetAsync(new{Name="National Museum of Nature and Science",Type="museum"});awaitcitiesRef.Document("BJ").Collection("landmarks").Document().SetAsync(new{Name="Jingshan Park",Type="park"});awaitcitiesRef.Document("BJ").Collection("landmarks").Document().SetAsync(new{Name="Beijing Ancient Observatory",Type="museum"});}}privatestaticasyncTaskCreateQueryState(stringproject){FirestoreDbdb=FirestoreDb.Create(project);CollectionReferencecitiesRef=db.Collection("cities");Queryquery=citiesRef.WhereEqualTo("State","CA");QuerySnapshotquerySnapshot=awaitquery.GetSnapshotAsync();foreach(DocumentSnapshotdocumentSnapshotinquerySnapshot.Documents){Console.WriteLine("Document {0} returned by query State=CA",documentSnapshot.Id);}}privatestaticasyncTaskCreateQueryCapital(stringproject){FirestoreDbdb=FirestoreDb.Create(project);CollectionReferencecitiesRef=db.Collection("cities");Queryquery=citiesRef.WhereEqualTo("Capital",true);QuerySnapshotquerySnapshot=awaitquery.GetSnapshotAsync();foreach(DocumentSnapshotdocumentSnapshotinquerySnapshot.Documents){Console.WriteLine("Document {0} returned by query Capital=true",documentSnapshot.Id);}}privatestaticasyncTaskSimpleQueries(stringproject){FirestoreDbdb=FirestoreDb.Create(project);CollectionReferencecitiesRef=db.Collection("cities");QuerystateQuery=citiesRef.WhereEqualTo("State","CA");QuerypopulationQuery=citiesRef.WhereGreaterThan("Population",1000000);QuerynameQuery=citiesRef.WhereGreaterThanOrEqualTo("Name","San Francisco");QuerySnapshotstateQuerySnapshot=awaitstateQuery.GetSnapshotAsync();foreach(DocumentSnapshotdocumentSnapshotinstateQuerySnapshot.Documents){Console.WriteLine("Document {0} returned by query State=CA",documentSnapshot.Id);}QuerySnapshotpopulationQuerySnapshot=awaitpopulationQuery.GetSnapshotAsync();foreach(DocumentSnapshotdocumentSnapshotinpopulationQuerySnapshot.Documents){Console.WriteLine("Document {0} returned by query Population>1000000",documentSnapshot.Id);}QuerySnapshotnameQuerySnapshot=awaitnameQuery.GetSnapshotAsync();foreach(DocumentSnapshotdocumentSnapshotinnameQuerySnapshot.Documents){Console.WriteLine("Document {0} returned by query Name>=San Francisco",documentSnapshot.Id);}}privatestaticasyncTaskArrayContainsQuery(stringproject){FirestoreDbdb=FirestoreDb.Create(project);CollectionReferencecitiesRef=db.Collection("cities");Queryquery=citiesRef.WhereArrayContains("Regions","west_coast");QuerySnapshotquerySnapshot=awaitquery.GetSnapshotAsync();foreach(DocumentSnapshotdocumentSnapshotinquerySnapshot.Documents){Console.WriteLine("Document {0} returned by query 'Regions array_contains west_coast'",documentSnapshot.Id);}}privatestaticasyncTaskArrayContainsAnyQuery(stringproject){FirestoreDbdb=FirestoreDb.Create(project);CollectionReferencecitiesRef=db.Collection("cities");Queryquery=citiesRef.WhereArrayContainsAny("Regions",new[]{"west_coast","east_coast"});QuerySnapshotquerySnapshot=awaitquery.GetSnapshotAsync();foreach(DocumentSnapshotdocumentSnapshotinquerySnapshot.Documents){Console.WriteLine("Document {0} returned by query 'Regions array_contains_any {{west_coast, east_coast}}'",documentSnapshot.Id);}}privatestaticasyncTaskInQueryWithoutArray(stringproject){FirestoreDbdb=FirestoreDb.Create(project);CollectionReferencecitiesRef=db.Collection("cities");Queryquery=citiesRef.WhereIn("Country",new[]{"USA","Japan"});QuerySnapshotquerySnapshot=awaitquery.GetSnapshotAsync();foreach(DocumentSnapshotdocumentSnapshotinquerySnapshot.Documents){Console.WriteLine("Document {0} returned by query 'Country in {{USA, Japan}}'",documentSnapshot.Id);}}privatestaticasyncTaskInQueryWithArray(stringproject){FirestoreDbdb=FirestoreDb.Create(project);CollectionReferencecitiesRef=db.Collection("cities");Queryquery=citiesRef.WhereIn("Regions",new[]{new[]{"west_coast"},new[]{"east_coast"}});QuerySnapshotquerySnapshot=awaitquery.GetSnapshotAsync();foreach(DocumentSnapshotdocumentSnapshotinquerySnapshot.Documents){Console.WriteLine("Document {0} returned by query 'Regions in {{west_coast}}, {{east_coast}}'",documentSnapshot.Id);}}privatestaticasyncTaskCollectionGroupQuery(stringproject){FirestoreDbdb=FirestoreDb.Create(project);Querymuseums=db.CollectionGroup("landmarks").WhereEqualTo("Type","museum");QuerySnapshotquerySnapshot=awaitmuseums.GetSnapshotAsync();foreach(DocumentSnapshotdocumentinquerySnapshot.Documents){Console.WriteLine($"{document.Reference.Path}: {document.GetValue<string>("Name")}");}}privatestaticasyncTaskSubcollectionQuery(stringproject){FirestoreDbdb=FirestoreDb.Create(project);CollectionReferencelandmarks=db.Collection("cities").Document("SF").Collection("landmarks");QuerySnapshotquerySnapshot=awaitlandmarks.GetSnapshotAsync();foreach(DocumentSnapshotdocumentinquerySnapshot.Documents){Console.WriteLine($"{document.Reference.Path}: {document.GetValue<string>("Name")}");}}privatestaticasyncTaskChainedQuery(stringproject){FirestoreDbdb=FirestoreDb.Create(project);CollectionReferencecitiesRef=db.Collection("cities");QuerychainedQuery=citiesRef.WhereEqualTo("State","CA").WhereEqualTo("Name","San Francisco");QuerySnapshotquerySnapshot=awaitchainedQuery.GetSnapshotAsync();foreach(DocumentSnapshotdocumentSnapshotinquerySnapshot.Documents){Console.WriteLine("Document {0} returned by query State=CA and Name=San Francisco",documentSnapshot.Id);}}privatestaticasyncTaskCompositeIndexChainedQuery(stringproject){FirestoreDbdb=FirestoreDb.Create(project);CollectionReferencecitiesRef=db.Collection("cities");QuerychainedQuery=citiesRef.WhereEqualTo("State","CA").WhereLessThan("Population",1000000);QuerySnapshotquerySnapshot=awaitchainedQuery.GetSnapshotAsync();foreach(DocumentSnapshotdocumentSnapshotinquerySnapshot.Documents){Console.WriteLine("Document {0} returned by query State=CA and Population<1000000",documentSnapshot.Id);}}privatestaticasyncTaskRangeQuery(stringproject){FirestoreDbdb=FirestoreDb.Create(project);CollectionReferencecitiesRef=db.Collection("cities");QueryrangeQuery=citiesRef.WhereGreaterThanOrEqualTo("State","CA").WhereLessThanOrEqualTo("State","IN");QuerySnapshotquerySnapshot=awaitrangeQuery.GetSnapshotAsync();foreach(DocumentSnapshotdocumentSnapshotinquerySnapshot.Documents){Console.WriteLine("Document {0} returned by query CA<=State<=IN",documentSnapshot.Id);}}privatestaticasyncTaskMultipleInequalitiesQuery(stringproject){FirestoreDbdb=FirestoreDb.Create(project);FirestoreAdminClientadminClient=FirestoreAdminClient.Create();varindex=newGoogle.Cloud.Firestore.Admin.V1.Index{Fields={newIndexField{FieldPath="Density",Order=IndexField.Types.Order.Ascending},newIndexField{FieldPath="Population",Order=IndexField.Types.Order.Ascending}},QueryScope=QueryScope.Collection};// We speculatively try to create the index, and just ignore an error of it already existing.try{varlro=awaitadminClient.CreateIndexAsync(newCollectionGroupName(db.ProjectId,db.DatabaseId,"cities"),index);awaitlro.PollUntilCompletedAsync();}catch(RpcExceptionex)when(ex.StatusCode==StatusCode.AlreadyExists){// Assume the index is okay.}CollectionReferencecitiesRef=db.Collection("cities");Queryquery=citiesRef.WhereGreaterThan("Population",1000000).WhereLessThan("Density",10000);QuerySnapshotquerySnapshot=awaitquery.GetSnapshotAsync();foreach(DocumentSnapshotdocumentSnapshotinquerySnapshot){varname=documentSnapshot.GetValue<string>("Name");varpopulation=documentSnapshot.GetValue<int>("Population");vardensity=documentSnapshot.GetValue<int>("Density");Console.WriteLine($"City '{name}' returned by query. Population={population}; Density={density}");}}publicstaticvoidMain(string[]args){if(args.Length <2){Console.Write(Usage);return;}stringcommand=args[0].ToLower();stringproject=string.Join(" ",newArraySegment<string>(args,1,args.Length-1));switch(command){case"query-create-examples":QueryCreateExamples(project).Wait();break;case"create-query-state":CreateQueryState(project).Wait();break;case"create-query-capital":CreateQueryCapital(project).Wait();break;case"simple-queries":SimpleQueries(project).Wait();break;case"array-contains-query":ArrayContainsQuery(project).Wait();break;case"array-contains-any-query":ArrayContainsAnyQuery(project).Wait();break;case"in-query":InQueryWithoutArray(project).Wait();break;case"in-query-array":InQueryWithArray(project).Wait();break;case"collection-group-query":CollectionGroupQuery(project).Wait();break;case"subcollection-query":SubcollectionQuery(project).Wait();break;case"chained-query":ChainedQuery(project).Wait();break;case"composite-index-chained-query":CompositeIndexChainedQuery(project).Wait();break;case"range-query":RangeQuery(project).Wait();break;case"multiple-inequalities":MultipleInequalitiesQuery(project).Wait();break;default:Console.Write(Usage);return;}}}}
Ruby
cities_ref=firestore.colcollection_pathsf_landmarks=cities_ref.document("SF").collection("landmarks")sf_landmarks.document.set({name:"Golden Gate Bridge",type:"bridge"})sf_landmarks.document.set({name:"Legion of Honor",type:"museum"})la_landmarks=cities_ref.document("LA").collection("landmarks")la_landmarks.document.set({name:"Griffith Park",type:"park"})la_landmarks.document.set({name:"The Getty",type:"museum"})dc_landmarks=cities_ref.document("DC").collection("landmarks")dc_landmarks.document.set({name:"Lincoln Memorial",type:"memorial"})dc_landmarks.document.set({name:"National Air and Space Museum",type:"museum"})tok_landmarks=cities_ref.document("TOK").collection("landmarks")tok_landmarks.document.set({name:"Ueno Park",type:"park"})tok_landmarks.document.set({name:"National Museum of Nature and Science",type:"museum"})bj_landmarks=cities_ref.document("BJ").collection("landmarks")bj_landmarks.document.set({name:"Jingshan Park",type:"park"})bj_landmarks.document.set({name:"Beijing Ancient Observatory",type:"museum"})

We can use the simple and compound query described earlier to query a singlecity'slandmarks subcollection, but you might also want to retrieveresults from every city'slandmarks subcollection at once.

Thelandmarks collection group consists of all collections with the IDlandmarks, and you can query it using a collection group query. For example,this collection group query retrieves allmuseum landmarks across all cities:

Web

import{collectionGroup,query,where,getDocs}from"firebase/firestore";constmuseums=query(collectionGroup(db,'landmarks'),where('type','==','museum'));constquerySnapshot=awaitgetDocs(museums);querySnapshot.forEach((doc)=>{console.log(doc.id,' => ',doc.data());});

Web

Learn more about the tree-shakeable modular Web API and its advantages over the namespaced API.
varmuseums=db.collectionGroup('landmarks').where('type','==','museum');museums.get().then((querySnapshot)=>{querySnapshot.forEach((doc)=>{console.log(doc.id,' => ',doc.data());});});
Swift
Note: This product is not available on watchOS and App Clip targets.
db.collectionGroup("landmarks").whereField("type",isEqualTo:"museum").getDocuments{(snapshot,error)in// ...}
Objective-C
Note: This product is not available on watchOS and App Clip targets.
[[[self.dbcollectionGroupWithID:@"landmarks"]queryWhereField:@"type"isEqualTo:@"museum"]getDocumentsWithCompletion:^(FIRQuerySnapshot*snapshot,NSError*error){// ...}];

Kotlin

db.collectionGroup("landmarks").whereEqualTo("type","museum").get().addOnSuccessListener{queryDocumentSnapshots->// ...}

Java

db.collectionGroup("landmarks").whereEqualTo("type","museum").get().addOnSuccessListener(newOnSuccessListener<QuerySnapshot>(){@OverridepublicvoidonSuccess(QuerySnapshotqueryDocumentSnapshots){// ...}});

Dart

db.collectionGroup("landmarks").where("type",isEqualTo:"museum").get().then((res)=>print("Successfully completed"),onError:(e)=>print("Error completing:$e"),);
Java
finalQuerymuseums=db.collectionGroup("landmarks").whereEqualTo("type","museum");finalApiFuture<QuerySnapshot>querySnapshot=museums.get();for(DocumentSnapshotdocument:querySnapshot.get().getDocuments()){System.out.println(document.getId());}
Python
museums=db.collection_group("landmarks").where(filter=FieldFilter("type","==","museum"))docs=museums.stream()fordocindocs:print(f"{doc.id} =>{doc.to_dict()}")

Python

museums=db.collection_group("landmarks").where(filter=FieldFilter("type","==","museum"))docs=museums.stream()asyncfordocindocs:print(f"{doc.id} =>{doc.to_dict()}")
C++
db->CollectionGroup("landmarks").WhereEqualTo("type",FieldValue::String("museum")).Get().OnCompletion([](constfirebase::Future<QuerySnapshot>&future){if(future.error()==Error::kErrorOk){for(constDocumentSnapshot&document:future.result()->documents()){std::cout <<document <<std::endl;}}else{std::cout <<"Error getting documents: " <<future.error_message()              <<std::endl;}});
Node.js
constquerySnapshot=awaitdb.collectionGroup('landmarks').where('type','==','museum').get();querySnapshot.forEach((doc)=>{console.log(doc.id,' => ',doc.data());});
Go
import("context""fmt""io""cloud.google.com/go/firestore""google.golang.org/api/iterator")// collectionGroupQuery runs a collection group query over the data created by// collectionGroupSetup.funccollectionGroupQuery(wio.Writer,projectIDstring)error{ctx:=context.Background()client,err:=firestore.NewClient(ctx,projectID)iferr!=nil{returnfmt.Errorf("firestore.NewClient: %w",err)}deferclient.Close()it:=client.CollectionGroup("landmarks").Where("type","==","museum").Documents(ctx)for{doc,err:=it.Next()iferr==iterator.Done{break}iferr!=nil{returnfmt.Errorf("documents iterator: %w",err)}fmt.Fprintf(w,"%s: %s",doc.Ref.ID,doc.Data()["name"])}returnnil}
PHP
$museums = $db->collectionGroup('landmarks')->where('type', '==', 'museum');foreach ($museums->documents() as $document) {    printf('%s => %s' . PHP_EOL, $document->id(), $document->data()['name']);}
Unity
Querymuseums=db.CollectionGroup("landmarks").WhereEqualTo("type","museum");museums.GetSnapshotAsync().ContinueWithOnMainThread((querySnapshotTask)=>{foreach(DocumentSnapshotdocumentSnapshotinquerySnapshotTask.Result.Documents){Debug.Log(String.Format("Document {0} returned by query State=CA",documentSnapshot.Id));}});
C#
Querymuseums=db.CollectionGroup("landmarks").WhereEqualTo("Type","museum");QuerySnapshotquerySnapshot=awaitmuseums.GetSnapshotAsync();foreach(DocumentSnapshotdocumentinquerySnapshot.Documents){Console.WriteLine($"{document.Reference.Path}: {document.GetValue<string>("Name")}");}
Ruby
museums=firestore.collection_group("landmarks").where("type","==","museum")museums.getdo|museum|puts"#{museum[:type]} name is#{museum[:name]}."end

Before using a collection group query, you must create an index thatsupports your collection group query.You can create an index through an error message, the console, or the Firebase CLI.

For the web and mobile SDKs, you must alsocreate rules that allow yourcollection group queries.

Explain your query performance

Cloud Firestore allows you to measure performance of your queries on thebackend and receive detailed performance statistics on backend query executionin return.

Query Explain results help you understand how your queries are executed, showingyou inefficiencies and the location of likely server-side bottlenecks.

For more information, see theguide for Query Explain.

Query limitations

The following list summarizesCloud Firestore query limitations:

  • Cloud Firestore provides support for logicalOR queriesthrough theor,in, andarray-contains-any operators. These queriesare limited to30 disjunctions based on the query's disjunctive normal form.This limit is fixed and cannot be adjusted.
  • You can use at most onearray-contains clause per disjunction (or group).You can't combinearray-contains witharray-contains-any in the samedisjunction.
  • You can't combinenot-in within,array-contains-any, oror in thesame query.
  • Only a singlenot-in or!= is allowed per query.
  • not-in supports up to 10 comparison values.
  • The sum of filters, sort orders, and parent document path (1 for a subcollection,0 for a root collection) in a query cannot exceed 100. This is calculatedbased on thedisjunctive normal form of the query.
  • A query with an inequality filter on a field implies ordering by thatfield andfilters for existence of that field.

Limits onOR queries

To prevent a query from becoming too computationally expensive,Cloud Firestore limits how manyAND andOR clauses you can combine.To apply this limit,Cloud Firestore converts queries that performlogicalOR operations (or,in, andarray-contains-any) todisjunctive normal form(also known as anOR ofANDs).Cloud Firestore limits a query to amaximum of 30 disjunctions in disjunctive normal form.This limit is fixed and cannot be adjusted.

Disjunctive normal form

Cloud Firestore converts queries to disjunctive normal formby applying two rules:

  • Flatten

    Given conditionsA,B, andC:

    A and (B and C) => A and B and C

  • Distributive Law

    Given conditionsA,B,C, andD:

    • 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)

When applying these rules toin andarray-contains-any queries, rememberthat these operators are shorthands forOR. For example,a in [1,2] isshorthand fora = 1 OR a = 2.

Warning: Due to the multiplicative nature of conversions to disjunctive normalform, you are more likely to reach the limit when performing anAND ofmultipleOR groups.

The following examples show the number of disjunctions for different queries:

QueryNumber of disjunctions
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

The disjunctive normal form of this query is equal to the query above.

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

This query returns an error, because it surpasses the limit of 30 disjunctions.

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 and existence

When you order a query by a given field, the query can return only thedocuments where the order-by field exists.

For example, the following query would not return any documents where thepopulation field is not set, even if they otherwise meet the query filters.

Java
db.collection("cities").whereEqualTo("country",USA).orderBy(population);

A related effect applies to inequalities. A query with an inequality filteron a field also implies ordering by that field. The followingquery does not return documents without apopulation field evenifcountry = USA in that document . As a workaround, you can executeseparate queries for each ordering or you can assign a value for all fieldsthat you order by.

Java
db.collection(cities).where(or(country,USA),greaterThan(population,250000));

The query above includes an implied order-by on the inequality and isequivalent to the following:

Java
db.collection(cities).where(or(country,USA),greaterThan(population,250000)).orderBy(population);

What's next

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-10-22 UTC.