Firebase is back at Google I/O on May 10! Register now

Toplama sorgularıyla belgeleri sayın

Koleksiyonlar ile düzeninizi koruyun İçeriği tercihlerinize göre kaydedin ve kategorilere ayırın.

Toplama sorgusu, tek bir özet değeri döndürmek için birden çok dizin girişinden gelen verileri işler.

Cloud Firestore count() toplama sorgusunu destekler. count() bir koleksiyon veya sorgudaki belge sayısını belirlemenizi sağlar. Sunucu, sayımı hesaplar ve yalnızca sonucu, tek bir tamsayıyı uygulamanıza geri iletir ve tam sorgunun yürütülmesine kıyasla hem faturalandırılmış belge okumalarından hem de aktarılan baytlardan tasarruf sağlar.

Toplama sorguları, sorgularınızın zaten kullandığı mevcut dizin yapılandırmasına dayanır ve taranan dizin girişlerinin sayısıyla orantılı olarak ölçeklenir. Bu, küçük ila orta ölçekli veri kümelerinin kümelerinin 20-40 ms içinde performans gösterdiği anlamına gelir, ancak sayılan öğe sayısıyla gecikme artar.

count() toplamasını kullanın

Veri alma bölümünde ayarladığımız örnek verilere bakın.

Aşağıdaki count() toplaması, cities koleksiyonundaki toplam şehir sayısını döndürür.

Web version 9

const coll = collection(db, "cities");
const snapshot = await getCountFromServer(coll);
console.log('count: ', snapshot.data().count);
Süratli
Not: Bu ürün, watchOS ve App Clip hedeflerinde mevcut değildir.
let query = db.collection("cities")
let countQuery = query.count
do {
    let snapshot = try await countQuery.getAggregation(source: .server)
    print(snapshot.count)
} catch {
    print(error);
}
Amaç-C
Not: Bu ürün, watchOS ve App Clip hedeflerinde mevcut değildir.
FIRCollectionReference *query = [self.db collectionWithPath:@"cities"];
[query.count aggregationWithSource:FIRAggregateSourceServer
                        completion:^(FIRAggregateQuerySnapshot *snapshot,
                                     NSError *error) {
    if (error != nil) {
        NSLog(@"Error fetching count: %@", error);
    } else {
        NSLog(@"Cities count: %@", snapshot.count);
    }
}];

Java

Query query = db.collection("cities");
AggregateQuery countQuery = query.count();
countQuery.get(AggregateSource.SERVER).addOnCompleteListener(new OnCompleteListener<AggregateQuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<AggregateQuerySnapshot> task) {
        if (task.isSuccessful()) {
            // Count fetched successfully
            AggregateQuerySnapshot snapshot = task.getResult();
            Log.d(TAG, "Count: " + snapshot.getCount());
        } else {
            Log.d(TAG, "Count failed: ", task.getException());
        }
    }
});

Kotlin+KTX

val query = db.collection("cities")
val countQuery = query.count()
countQuery.get(AggregateSource.SERVER).addOnCompleteListener { task ->
    if (task.isSuccessful) {
        // Count fetched successfully
        val snapshot = task.result
        Log.d(TAG, "Count: ${snapshot.count}")
    } else {
        Log.d(TAG, "Count failed: ", task.getException())
    }
}

Java

CollectionReference collection = db.collection("cities");
AggregateQuery countQuery = collection.count();
countQuery.get(AggregateSource.SERVER).addOnCompleteListener(task -> {
  if (task.isSuccessful()) {
    AggregateQuerySnapshot snapshot = task.getResult();
    Log.d(TAG, "Count: " + snapshot.getCount());
  } else {
    Log.d(TAG, "Count failed: ", task.getException());
  }
});
      
java
CollectionReference collection = db.collection("cities");
AggregateQuerySnapshot snapshot = collection.count().get().get();
System.out.println("Count: " + snapshot.getCount());
      
Node.js
const collectionRef = db.collection('cities');
const snapshot = await collectionRef.count().get();
console.log(snapshot.data().count);
      

count() toplaması, sorgudaki tüm filtreleri ve tüm limit yan tümcelerini hesaba katar. Örneğin, aşağıdaki toplama, state CA değerine eşit olduğu şehirlerin sayısını döndürür.

Web version 9

const coll = collection(db, "cities");
const q = query(coll, where("state", "==", "CA"));
const snapshot = await getCountFromServer(q);
console.log('count: ', snapshot.data().count);
Süratli
Not: Bu ürün, watchOS ve App Clip hedeflerinde mevcut değildir.
let query = db.collection("cities").whereField("state", isEqualTo: "CA")
let countQuery = query.count
do {
    let snapshot = try await countQuery.getAggregation(source: .server)
    print(snapshot.count)
} catch {
    print(error);
}
Amaç-C
Not: Bu ürün, watchOS ve App Clip hedeflerinde mevcut değildir.
FIRQuery *query =
    [[self.db collectionWithPath:@"cities"]
                 queryWhereField:@"state"
                       isEqualTo:@"CA"];
[query.count aggregationWithSource:FIRAggregateSourceServer
                        completion:^(FIRAggregateQuerySnapshot *snapshot,
                                      NSError *error) {
    if (error != nil) {
        NSLog(@"Error fetching count: %@", error);
    } else {
        NSLog(@"Cities count: %@", snapshot.count);
    }
}];

Java

Query query = db.collection("cities").whereEqualTo("state", "CA");
AggregateQuery countQuery = query.count();
countQuery.get(AggregateSource.SERVER).addOnCompleteListener(new OnCompleteListener<AggregateQuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<AggregateQuerySnapshot> task) {
        if (task.isSuccessful()) {
            // Count fetched successfully
            AggregateQuerySnapshot snapshot = task.getResult();
            Log.d(TAG, "Count: " + snapshot.getCount());
        } else {
            Log.d(TAG, "Count failed: ", task.getException());
        }
    }
});

Kotlin+KTX

val query = db.collection("cities").whereEqualTo("state", "CA")
val countQuery = query.count()
countQuery.get(AggregateSource.SERVER).addOnCompleteListener { task ->
    if (task.isSuccessful) {
        // Count fetched successfully
        val snapshot = task.result
        Log.d(TAG, "Count: ${snapshot.count}")
    } else {
        Log.d(TAG, "Count failed: ", task.getException())
    }
}

Java

CollectionReference collection = db.collection("cities");
Query query = collection.whereEqualTo("state", "CA");
AggregateQuery countQuery = query.count();
countQuery.get(AggregateSource.SERVER).addOnCompleteListener(task -> {
  if (task.isSuccessful()) {
    AggregateQuerySnapshot snapshot = task.getResult();
    Log.d(TAG, "Count: " + snapshot.getCount());
  } else {
    Log.d(TAG, "Count failed: ", task.getException());
  }
});
      
java
CollectionReference collection = db.collection("cities");
Query query = collection.whereEqualTo("state", "CA");
AggregateQuerySnapshot snapshot = query.count().get().get();
System.out.println("Count: " + snapshot.getCount());
      
Node.js
const collectionRef = db.collection('cities');
const query = collectionRef.where('state', '==', 'CA');
const snapshot = await query.count().get();
console.log(snapshot.data().count);
      

Cloud Firestore Güvenlik Kuralları, count() toplama sorgularında, belgeleri döndüren normal sorgularda olduğu gibi çalışır. Diğer bir deyişle, ancak ve ancak kurallarınız istemcilerin belirli toplama veya toplama grubu sorgularını yürütmesine izin veriyorsa, istemciler de bu sorgularda count() toplama işlemini gerçekleştirebilir. Cloud Firestore Güvenlik Kurallarının sorgularla nasıl etkileşime girdiği hakkında daha fazla bilgi edinin.

sınırlamalar

count() toplama sorgusunda aşağıdaki sınırlamalara dikkat edin:

  • count() toplama sorguları şu anda yalnızca doğrudan sunucu yanıtı aracılığıyla desteklenmektedir. Sorgular, yerel önbellek ve arabelleğe alınan güncellemeler atlanarak yalnızca Cloud Firestore arka ucu tarafından sunulur. Bu davranış, Cloud Firestore işlemleri içinde gerçekleştirilen işlemlerle aynıdır. Şu anda count() sorgularını gerçek zamanlı dinleyiciler ve çevrimdışı sorgularla kullanamazsınız.

  • Bir count() toplaması 60 saniye içinde çözümlenemezse, bir DEADLINE_EXCEEDED hatası döndürür. Performans, dizin yapılandırmanıza ve veri kümesinin boyutuna bağlıdır.

    İşlem 60 saniyelik son tarih içinde tamamlanamazsa, olası bir geçici çözüm, büyük veri kümeleri için sayaç kullanmaktır.

  • count() toplaması, dizin girişlerinden okur ve yalnızca dizine eklenmiş alanları sayar.

  • Sorguya bir OrderBy yan tümcesi eklemek, sıralama özelliğinin bulunduğu varlıkların sayısını sınırlar.

Fiyatlandırma

count() için fiyatlandırma, sorgu tarafından eşleşen dizin girişlerinin sayısına bağlıdır. Çok sayıda eşleşen giriş için az sayıda okuma için ücretlendirilirsiniz.

Daha ayrıntılı fiyatlandırma bilgilerine bakın.