Performing Simple and Compound Queries with Cloud Firestore

Cloud Firestore provides powerful query functionality for specifying which documents you want to retrieve from a collection. These queries can also be used with either get() or addSnapshotListener(), as described in Get Data and Get Realtime Updates.

Example data

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

Web
var citiesRef = db.collection("cities");

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

citiesRef.document("SF").setData([
    "name": "San Francisco",
    "state": "CA",
    "country": "USA",
    "capital": false,
    "population": 860000,
    "regions": ["west_coast", "norcal"]
    ])
citiesRef.document("LA").setData([
    "name": "Los Angeles",
    "state": "CA",
    "country": "USA",
    "capital": false,
    "population": 3900000,
    "regions": ["west_coast", "socal"]
    ])
citiesRef.document("DC").setData([
    "name": "Washington D.C.",
    "country": "USA",
    "capital": true,
    "population": 680000,
    "regions": ["east_coast"]
    ])
citiesRef.document("TOK").setData([
    "name": "Tokyo",
    "country": "Japan",
    "capital": true,
    "population": 9000000,
    "regions": ["kanto", "honshu"]
    ])
citiesRef.document("BJ").setData([
    "name": "Beijing",
    "country": "China",
    "capital": true,
    "population": 21500000,
    "regions": ["jingjinji", "hebei"]
    ])
Objective-C
FIRCollectionReference *citiesRef = [self.db collectionWithPath:@"cities"];
[[citiesRef documentWithPath:@"SF"] setData:@{
  @"name": @"San Francisco",
  @"state": @"CA",
  @"country": @"USA",
  @"capital": @(NO),
  @"population": @860000,
  @"regions": @[@"west_coast", @"norcal"]
}];
[[citiesRef documentWithPath:@"LA"] setData:@{
  @"name": @"Los Angeles",
  @"state": @"CA",
  @"country": @"USA",
  @"capital": @(NO),
  @"population": @3900000,
  @"regions": @[@"west_coast", @"socal"]
}];
[[citiesRef documentWithPath:@"DC"] setData:@{
  @"name": @"Washington D.C.",
  @"country": @"USA",
  @"capital": @(YES),
  @"population": @680000,
  @"regions": @[@"east_coast"]
}];
[[citiesRef documentWithPath:@"TOK"] setData:@{
  @"name": @"Tokyo",
  @"country": @"Japan",
  @"capital": @(YES),
  @"population": @9000000,
  @"regions": @[@"kanto", @"honshu"]
}];
[[citiesRef documentWithPath:@"BJ"] setData:@{
  @"name": @"Beijing",
  @"country": @"China",
  @"capital": @(YES),
  @"population": @21500000,
  @"regions": @[@"jingjinji", @"hebei"]
}];
  
Java
Android
CollectionReference cities = db.collection("cities");

Map<String, Object> data1 = new HashMap<>();
data1.put("name", "San Francisco");
data1.put("state", "CA");
data1.put("country", "USA");
data1.put("capital", false);
data1.put("population", 860000);
data1.put("regions", Arrays.asList("west_coast", "norcal"));
cities.document("SF").set(data1);

Map<String, Object> data2 = new HashMap<>();
data2.put("name", "Los Angeles");
data2.put("state", "CA");
data2.put("country", "USA");
data2.put("capital", false);
data2.put("population", 3900000);
data2.put("regions", Arrays.asList("west_coast", "socal"));
cities.document("LA").set(data2);

Map<String, Object> data3 = new HashMap<>();
data3.put("name", "Washington D.C.");
data3.put("state", null);
data3.put("country", "USA");
data3.put("capital", true);
data3.put("population", 680000);
data3.put("regions", Arrays.asList("east_coast"));
cities.document("DC").set(data3);

Map<String, Object> data4 = new HashMap<>();
data4.put("name", "Tokyo");
data4.put("state", null);
data4.put("country", "Japan");
data4.put("capital", true);
data4.put("population", 9000000);
data4.put("regions", Arrays.asList("kanto", "honshu"));
cities.document("TOK").set(data4);

Map<String, Object> data5 = new HashMap<>();
data5.put("name", "Beijing");
data5.put("state", null);
data5.put("country", "China");
data5.put("capital", true);
data5.put("population", 21500000);
data5.put("regions", Arrays.asList("jingjinji", "hebei"));
cities.document("BJ").set(data5);
Kotlin
Android
val cities = db.collection("cities")

val data1 = HashMap<String, Any>()
data1["name"] = "San Francisco"
data1["state"] = "CA"
data1["country"] = "USA"
data1["capital"] = false
data1["population"] = 860000
data1["regions"] = listOf("west_coast", "norcal")
cities.document("SF").set(data1)

val data2 = HashMap<String, Any>()
data2["name"] = "Los Angeles"
data2["state"] = "CA"
data2["country"] = "USA"
data2["capital"] = false
data2["population"] = 3900000
data2["regions"] = listOf("west_coast", "socal")
cities.document("LA").set(data2)

val data3 = HashMap<String, Any?>()
data3["name"] = "Washington D.C."
data3["state"] = null
data3["country"] = "USA"
data3["capital"] = true
data3["population"] = 680000
data3["regions"] = listOf("east_coast")
cities.document("DC").set(data3)

val data4 = HashMap<String, Any?>()
data4["name"] = "Tokyo"
data4["state"] = null
data4["country"] = "Japan"
data4["capital"] = true
data4["population"] = 9000000
data4["regions"] = listOf("kanto", "honshu")
cities.document("TOK").set(data4)

val data5 = HashMap<String, Any?>()
data5["name"] = "Beijing"
data5["state"] = null
data5["country"] = "China"
data5["capital"] = true
data5["population"] = 21500000
data5["regions"] = listOf("jingjinji", "hebei")
cities.document("BJ").set(data5)
Java
CollectionReference cities = db.collection("cities");
List<ApiFuture<WriteResult>> futures = new ArrayList<>();
futures.add(cities.document("SF").set(new City("San Francisco", "CA", "USA", false, 860000L,
    Arrays.asList("west_coast", "norcal"))));
futures.add(cities.document("LA").set(new City("Los Angeles", "CA", "USA", false, 3900000L,
    Arrays.asList("west_coast", "socal"))));
futures.add(cities.document("DC").set(new City("Washington D.C.", null, "USA", true, 680000L,
    Arrays.asList("east_coast"))));
futures.add(cities.document("TOK").set(new City("Tokyo", null, "Japan", true, 9000000L,
    Arrays.asList("kanto", "honshu"))));
futures.add(cities.document("BJ").set(new City("Beijing", null, "China", true, 21500000L,
    Arrays.asList("jingjinji", "hebei"))));
// (optional) block on documents successfully added
ApiFutures.allAsList(futures).get();
Python
class City(object):
    def __init__(self, name, state, country, capital=False, population=0):
        self.name = name
        self.state = state
        self.country = country
        self.capital = capital
        self.population = population

    @staticmethod
    def from_dict(source):
        # ...

    def to_dict(self):
        # ...

    def __repr__(self):
        return u'City(name={}, country={}, population={}, capital={})'.format(
            self.name, self.country, self.population, self.capital)

cities_ref = db.collection(u'cities')
cities_ref.document(u'SF').set(
    City(u'San Francisco', u'CA', u'USA', False, 860000).to_dict())
cities_ref.document(u'LA').set(
    City(u'Los Angeles', u'CA', u'USA', False, 3900000).to_dict())
cities_ref.document(u'DC').set(
    City(u'Washington D.C.', None, u'USA', True, 680000).to_dict())
cities_ref.document(u'TOK').set(
    City(u'Tokyo', None, u'Japan', True, 9000000).to_dict())
cities_ref.document(u'BJ').set(
    City(u'Beijing', None, u'China', True, 21500000).to_dict())
Node.js
var citiesRef = db.collection('cities');

var setSf = citiesRef.doc('SF').set({
  name: 'San Francisco', state: 'CA', country: 'USA',
  capital: false, population: 860000,
  regions: ['west_coast', 'norcal']
});
var setLa = citiesRef.doc('LA').set({
  name: 'Los Angeles', state: 'CA', country: 'USA',
  capital: false, population: 3900000,
  regions: ['west_coast', 'socal']
});
var setDc = citiesRef.doc('DC').set({
  name: 'Washington, D.C.', state: null, country: 'USA',
  capital: true, population: 680000,
  regions: ['east_coast']
});
var setTok = citiesRef.doc('TOK').set({
  name: 'Tokyo', state: null, country: 'Japan',
  capital: true, population: 9000000,
  regions: ['kanto', 'honshu']
});
var setBj = citiesRef.doc('BJ').set({
  name: 'Beijing', state: null, country: 'China',
  capital: true, population: 21500000,
  regions: ['jingjinji', 'hebei']
});
Go
cities := []struct {
	id string
	c  City
}{
	{
		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: false, 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 := range cities {
	if _, err := client.Collection("cities").Doc(c.id).Set(ctx, c.c); err != nil {
		return err
	}
}
PHP
$citiesRef = $db->collection('cities');
$citiesRef->document('SF')->set([
    'name' => 'San Francisco',
    'state' => 'CA',
    'country' => 'USA',
    'capital' => false,
    'population' => 860000,
    'regions' => ['west_coast', 'norcal']
]);
$citiesRef->document('LA')->set([
    'name' => 'Los Angeles',
    'state' => 'CA',
    'country' => 'USA',
    'capital' => false,
    'population' => 3900000,
    'regions' => ['west_coast', 'socal']
]);
$citiesRef->document('DC')->set([
    'name' => 'Washington D.C.',
    'state' => null,
    'country' => 'USA',
    'capital' => true,
    'population' => 680000,
    'regions' => ['east_coast']
]);
$citiesRef->document('TOK')->set([
    'name' => 'Tokyo',
    'state' => null,
    'country' => 'Japan',
    'capital' => true,
    'population' => 9000000,
    'regions' => ['kanto', 'honshu']
]);
$citiesRef->document('BJ')->set([
    'name' => 'Beijing',
    'state' => null,
    'country' => 'China',
    'capital' => true,
    'population' => 21500000,
    'regions' => ['jingjinji', 'hebei']
]);
printf('Added example cities data to the cities collection.' . PHP_EOL);
C#
CollectionReference citiesRef = db.Collection("cities");
await citiesRef.Document("SF").SetAsync(new Dictionary<string, object>(){
    { "Name", "San Francisco" },
    { "State", "CA" },
    { "Country", "USA" },
    { "Capital", false },
    { "Population", 860000 },
    { "Regions", new ArrayList{"west_coast", "norcal"} }
});
await citiesRef.Document("LA").SetAsync(new Dictionary<string, object>(){
    { "Name", "Los Angeles" },
    { "State", "CA" },
    { "Country", "USA" },
    { "Capital", false },
    { "Population", 3900000 },
    { "Regions", new ArrayList{"west_coast", "socal"} }
});
await citiesRef.Document("DC").SetAsync(new Dictionary<string, object>(){
    { "Name", "Washington D.C." },
    { "State", null },
    { "Country", "USA" },
    { "Capital", true },
    { "Population", 680000 },
    { "Regions", new ArrayList{"east_coast"} }
});
await citiesRef.Document("TOK").SetAsync(new Dictionary<string, object>(){
    { "Name", "Tokyo" },
    { "State", null },
    { "Country", "Japan" },
    { "Capital", true },
    { "Population", 9000000 },
    { "Regions", new ArrayList{"kanto", "honshu"} }
});
await citiesRef.Document("BJ").SetAsync(new Dictionary<string, object>(){
    { "Name", "Beijing" },
    { "State", null },
    { "Country", "China" },
    { "Capital", true },
    { "Population", 21500000 },
    { "Regions", new ArrayList{"jingjinji", "hebei"} }
});
Console.WriteLine("Added example cities data to the cities collection.");
Ruby
cities_ref = firestore.col "cities"
cities_ref.doc("SF").set({
  name:       "San Francisco",
  state:      "CA",
  country:    "USA",
  capital:    false,
  population: 860000
})
cities_ref.doc("LA").set({
  name:       "Los Angeles",
  state:      "CA",
  country:    "USA",
  capital:    false,
  population: 3900000
})
cities_ref.doc("DC").set({
  name:       "Washington D.C.",
  state:      nil,
  country:    "USA",
  capital:    true,
  population: 680000
})
cities_ref.doc("TOK").set({
  name:       "Tokyo",
  state:      nil,
  country:    "Japan",
  capital:    true,
  population: 9000000
})
cities_ref.doc("BJ").set({
  name:       "Beijing",
  state:      nil,
  country:    "China",
  capital:    true,
  population: 21500000
})

Simple queries

The following query returns all cities with state CA:

Web
// Create a reference to the cities collection
var citiesRef = db.collection("cities");

// Create a query against the collection.
var query = citiesRef.where("state", "==", "CA");
Swift
// Create a reference to the cities collection
let citiesRef = db.collection("cities")

// Create a query against the collection.
let query = citiesRef.whereField("state", isEqualTo: "CA")
Objective-C
// Create a reference to the cities collection
FIRCollectionReference *citiesRef = [self.db collectionWithPath:@"cities"];
// Create a query against the collection.
FIRQuery *query = [citiesRef queryWhereField:@"state" isEqualTo:@"CA"];
  
Java
Android
// Create a reference to the cities collection
CollectionReference citiesRef = db.collection("cities");

// Create a query against the collection.
Query query = citiesRef.whereEqualTo("state", "CA");
Kotlin
Android
// Create a reference to the cities collection
val citiesRef = db.collection("cities")

// Create a query against the collection.
val query = citiesRef.whereEqualTo("state", "CA")
Java
// Create a reference to the cities collection
CollectionReference cities = db.collection("cities");
// Create a query against the collection.
Query query = cities.whereEqualTo("state", "CA");
// retrieve  query results asynchronously using query.get()
ApiFuture<QuerySnapshot> querySnapshot = query.get();

for (DocumentSnapshot document : querySnapshot.get().getDocuments()) {
  System.out.println(document.getId());
}
Python
# Create a reference to the cities collection
cities_ref = db.collection(u'cities')

# Create a query against the collection
query_ref = cities_ref.where(u'state', u'==', u'CA')
Node.js
// Create a reference to the cities collection
var citiesRef = db.collection('cities');

// Create a query against the collection
var queryRef = citiesRef.where('state', '==', 'CA');
Go
query := client.Collection("cities").Where("state", "==", "CA")
PHP
$citiesRef = $db->collection('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());
}
C#
CollectionReference citiesRef = db.Collection("cities");
Query query = citiesRef.WhereEqualTo("State", "CA");
QuerySnapshot querySnapshot = await query.GetSnapshotAsync();
foreach (DocumentSnapshot documentSnapshot in querySnapshot.Documents)
{
    Console.WriteLine("Document {0} returned by query State=CA", documentSnapshot.Id);
}
Ruby
cities_ref = firestore.col "cities"

query = cities_ref.where "state", "=", "CA"

query.get do |city|
  puts "Document #{city.document_id} returned by query state=CA."
end

The following query returns all the capital cities:

Web
var citiesRef = db.collection("cities");

var query = citiesRef.where("capital", "==", true);
Swift
let capitalCities = db.collection("cities").whereField("capital", isEqualTo: true)
Objective-C
FIRQuery *capitalCities =
    [[self.db collectionWithPath:@"cities"] queryWhereField:@"capital" isEqualTo:@YES];
  
Java
Android
Query capitalCities = db.collection("cities").whereEqualTo("capital", true);
Kotlin
Android
val capitalCities = db.collection("cities").whereEqualTo("capital", true)
Java
// Create a reference to the cities collection
CollectionReference cities = db.collection("cities");
// Create a query against the collection.
Query query = cities.whereEqualTo("capital", true);
// retrieve  query results asynchronously using query.get()
ApiFuture<QuerySnapshot> querySnapshot = query.get();

for (DocumentSnapshot document : querySnapshot.get().getDocuments()) {
  System.out.println(document.getId());
}
Python
cities_ref = db.collection(u'cities')

query = cities_ref.where(u'capital', u'==', True)
Node.js
// Create a reference to the cities collection
var citiesRef = db.collection('cities');

// Create a query against the collection
var queryRef = citiesRef.where('capital', '==', true);
Go
query := client.Collection("cities").Where("capital", "==", true)
PHP
$citiesRef = $db->collection('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());
}
C#
CollectionReference citiesRef = db.Collection("cities");
Query query = citiesRef.WhereEqualTo("Capital", true);
QuerySnapshot querySnapshot = await query.GetSnapshotAsync();
foreach (DocumentSnapshot documentSnapshot in querySnapshot.Documents)
{
    Console.WriteLine("Document {0} returned by query Capital=true", documentSnapshot.Id);
}
Ruby
cities_ref = firestore.col "cities"

query = cities_ref.where "capital", "=", true

query.get do |city|
  puts "Document #{city.document_id} returned by query capital=true."
end

The where() method takes three parameters: a field to filter on, a comparison operation, and a value. The comparison can be <, <=, ==, >, >=, or array_contains. For iOS, Android, and Java, the comparison operator is explicitly named in the method.

Some example filters:

Web
citiesRef.where("state", "==", "CA")
citiesRef.where("population", "<", 100000)
citiesRef.where("name", ">=", "San Francisco")
Swift
citiesRef.whereField("state", isEqualTo: "CA")
citiesRef.whereField("population", isLessThan: 100000)
citiesRef.whereField("name", isGreaterThanOrEqualTo: "San Francisco")
Objective-C
[citiesRef queryWhereField:@"state" isEqualTo:@"CA"];
[citiesRef queryWhereField:@"population" isLessThan:@100000];
[citiesRef queryWhereField:@"name" isGreaterThanOrEqualTo:@"San Francisco"];
  
Java
Android
citiesRef.whereEqualTo("state", "CA");
citiesRef.whereLessThan("population", 100000);
citiesRef.whereGreaterThanOrEqualTo("name", "San Francisco");
Kotlin
Android
citiesRef.whereEqualTo("state", "CA")
citiesRef.whereLessThan("population", 100000)
citiesRef.whereGreaterThanOrEqualTo("name", "San Francisco")
Java
Query countryQuery = cities.whereEqualTo("state", "CA");
Query populationQuery = cities.whereLessThan("population", 1000000L);
Query cityQuery = cities.whereGreaterThanOrEqualTo("name", "San Francisco");
Python
cities_ref = db.collection(u'cities')

cities_ref.where(u'state', u'==', u'CA')
cities_ref.where(u'population', u'<', 1000000)
cities_ref.where(u'name', u'>=', u'San Francisco')
Node.js
var brazilCities = citiesRef.where('state', '==', 'CA');
var smallCities = citiesRef.where('population', '<', 1000000);
var afterParis = citiesRef.where('name', '>=', 'San Francisco');
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');
C#
Query stateQuery = citiesRef.WhereEqualTo("State", "CA");
Query populationQuery = citiesRef.WhereGreaterThan("Population", 1000000);
Query nameQuery = citiesRef.WhereGreaterThanOrEqualTo("Name", "San Francisco");
Ruby
state_query      = cities_ref.where "state", "=", "CA"
population_query = cities_ref.where "population", ">", 1000000
name_query       = cities_ref.where "name", ">=", "San Francisco"

Array membership

You can use the array_contains operator to filter based on array values. For example:

Web
citiesRef.where("regions", "array-contains", "west_coast")
Swift
citiesRef
  .whereField("regions", arrayContains: "west_coast")
Objective-C
[citiesRef queryWhereField:@"state" arrayContains:@"west_coast"];
  
Java
Android
CollectionReference citiesRef = db.collection("cities");

citiesRef.whereArrayContains("regions", "west_coast");
Kotlin
Android
val citiesRef = db.collection("cities")

citiesRef.whereArrayContains("regions", "west_coast")
Java
CollectionReference citiesRef = db.collection("cities");
Query westCoastQuery = citiesRef.whereArrayContains("regions", "west_coast");
Python
// Not supported yet
Node.js
var westCoastCities = citiesRef.where('regions', 'array-contains',
  'west_coast');
Go
query := cities.Where("regions", "array-contains", "west_coast").Documents(ctx)
PHP
$containsQuery = $citiesRef->where('regions', 'array-contains', 'west_coast');
C#
Query query = citiesRef.WhereArrayContains("Regions", "west_coast");
Ruby
// Not supported yet

This query returns every city document where the regions field is an array that contains west_coast. If the array has multiple instances of the value you query on, the document is included in the results only once.

Compound queries

You can also chain multiple where() methods to create more specific queries (logical AND). However, to combine the equality operator (==) with a range or array-contains clause (<, <=, >, >=, or array_contains), make sure to create a composite index.

Web
citiesRef.where("state", "==", "CO").where("name", "==", "Denver")
citiesRef.where("state", "==", "CA").where("population", "<", 1000000)
Swift
citiesRef
    .whereField("state", isEqualTo: "CO")
    .whereField("name", isEqualTo: "Denver")
citiesRef
    .whereField("state", isEqualTo: "CA")
    .whereField("population", isLessThan: 1000000)
Objective-C
[[citiesRef queryWhereField:@"state" isEqualTo:@"CO"]
    queryWhereField:@"name" isGreaterThanOrEqualTo:@"Denver"];
[[citiesRef queryWhereField:@"state" isEqualTo:@"CA"]
    queryWhereField:@"population" isLessThan:@1000000];
  
Java
Android
citiesRef.whereEqualTo("state", "CO").whereEqualTo("name", "Denver");
citiesRef.whereEqualTo("state", "CA").whereLessThan("population", 1000000);
Kotlin
Android
citiesRef.whereEqualTo("state", "CO").whereEqualTo("name", "Denver")
citiesRef.whereEqualTo("state", "CA").whereLessThan("population", 1000000)
Java
Query chainedQuery1 = cities.whereEqualTo("state", "CO")
    .whereEqualTo("name", "Denver");
Query chainedQuery2 = cities.whereEqualTo("state", "CA")
    .whereLessThan("population", 1000000L);
Python
cities_ref = db.collection(u'cities')

sydney_query = cities_ref.where(
    u'state', u'==', u'CO').where(u'name', u'==', u'Denver')
large_us_cities_query = cities_ref.where(
    u'state', u'==', u'CA').where(u'population', u'>', 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');
$chainedQuery = $citiesRef
    ->where('state', '=', 'CA')
    ->where('population', '<', 1000000);
C#
Query chainedQuery = citiesRef
    .WhereEqualTo("State", "CA")
    .WhereEqualTo("Name", "San Francisco");
Query chainedQuery = citiesRef
    .WhereEqualTo("State", "CA")
    .WhereLessThan("Population", 1000000);
Ruby
chained_query = cities_ref.where("state", "=", "CA").where("name", "=", "San Francisco")
chained_query = cities_ref.where("state", "=", "CA").where("population", "<", 1000000)

You can only perform range comparisons (<, <=, >, >=) on a single field, and you can include at most one array_contains clause in a compound query:

Valid: Range filters on only one field

Web
citiesRef.where("state", ">=", "CA").where("state", "<=", "IN")
citiesRef.where("state", "==", "CA").where("population", ">", 1000000)
Swift
citiesRef
    .whereField("state", isGreaterThanOrEqualTo: "CA")
    .whereField("state", isLessThanOrEqualTo: "IN")
citiesRef
    .whereField("state", isEqualTo: "CA")
    .whereField("population", isGreaterThan: 1000000)
Objective-C
[[citiesRef queryWhereField:@"state" isGreaterThanOrEqualTo:@"CA"]
    queryWhereField:@"state" isLessThanOrEqualTo:@"IN"];
[[citiesRef queryWhereField:@"state" isEqualTo:@"CA"]
    queryWhereField:@"population" isGreaterThan:@1000000];
  
Java
Android
citiesRef.whereGreaterThanOrEqualTo("state", "CA")
        .whereLessThanOrEqualTo("state", "IN");
citiesRef.whereEqualTo("state", "CA")
        .whereGreaterThan("population", 1000000);
Kotlin
Android
citiesRef.whereGreaterThanOrEqualTo("state", "CA")
        .whereLessThanOrEqualTo("state", "IN")
citiesRef.whereEqualTo("state", "CA")
        .whereGreaterThan("population", 1000000)
Java
Query validQuery1 = cities.whereGreaterThanOrEqualTo("state", "CA")
    .whereLessThanOrEqualTo("state", "IN");
Query validQuery2 = cities.whereEqualTo("state", "CA")
    .whereGreaterThan("population", 1000000);
Python
cities_ref = db.collection(u'cities')
cities_ref.where(u'state', u'>=', u'CA').where(u'state', u'<=', u'IN')
Node.js
citiesRef.where('state', '>=', 'CA').where('state', '<=', 'IN');
citiesRef.where('state', '==', 'CA').where('population', '>', 1000000);
Go
stateQuery := cities.Where("state", ">=", "CA").Where("state", "<", "IN")
populationQuery := cities.Where("state", "==", "CA").Where("population", ">", 1000000)
PHP
$rangeQuery = $citiesRef
    ->where('state', '>=', 'CA')
    ->where('state', '<=', 'IN');
C#
Query rangeQuery = citiesRef
    .WhereGreaterThanOrEqualTo("State", "CA")
    .WhereLessThanOrEqualTo("State", "IN");
Ruby
range_query = cities_ref.where("state", ">=", "CA").where("state", "<=", "IN")

Invalid: Range filters on different fields

Web
citiesRef.where("state", ">=", "CA").where("population", ">", 100000)
Swift
citiesRef
    .whereField("state", isGreaterThanOrEqualTo: "CA")
    .whereField("population", isGreaterThan: 1000000)
Objective-C
[[citiesRef queryWhereField:@"state" isGreaterThanOrEqualTo:@"CA"]
    queryWhereField:@"population" isGreaterThan:@1000000];
  
Java
Android
citiesRef.whereGreaterThanOrEqualTo("state", "CA").whereGreaterThan("population", 100000);
Kotlin
Android
citiesRef.whereGreaterThanOrEqualTo("state", "CA")
        .whereGreaterThan("population", 100000)
Java
Query invalidRangeQuery = cities.whereGreaterThanOrEqualTo("state", "CA")
    .whereGreaterThan("population", 100000);
Python
cities_ref = db.collection(u'cities')
cities_ref.where(
    u'state', u'>=', u'CA').where(u'population', u'>=', 1000000)
Node.js
citiesRef.where('state', '>=', 'CA').where('population', '>', 1000000);
Go
query := cities.Where("state", ">=", "CA").Where("population", ">", 1000000)
PHP
$invalidRangeQuery = $citiesRef
    ->where('state', '>=', 'CA')
    ->where('population', '>', 1000000);
C#
Query invalidRangeQuery = citiesRef
    .WhereGreaterThanOrEqualTo("State", "CA")
    .WhereGreaterThan("Population", 1000000);
Ruby
invalid_range_query = cities_ref.where("state", ">=", "CA").where("population", ">", 1000000)

Query limitations

Cloud Firestore does not support the following types of queries:

  • Queries with range filters on different fields, as described in the previous section.
  • Single queries across multiple collections or subcollections. Each query runs against a single collection of documents. For more information about how your data structure affects your queries, see Choose a Data Structure.
  • Logical OR queries. In this case, you should create a separate query for each OR condition and merge the query results in your app.
  • Queries with a != clause. In this case, you should split the query into a greater-than query and a less-than query. For example, although the query clause where("age", "!=", "30") is not supported, you can get the same result set by combining two queries, one with the clause where("age", "<", "30") and one with the clause where("age", ">", 30).
Was this page helpful? Let us know how we did:

Send feedback about...

Cloud Firestore