Catch up on highlights from Firebase at Google I/O 2023. Learn more

นับเอกสารด้วยแบบสอบถามการรวม

คิวรีแบบรวมจะประมวลผลข้อมูลจากรายการดัชนีหลายรายการเพื่อส่งคืนค่าสรุปค่าเดียว

Cloud Firestore รองรับการสอบถามการรวม count() count() ช่วยให้คุณกำหนดจำนวนเอกสารในคอลเลกชันหรือแบบสอบถาม เซิร์ฟเวอร์จะคำนวณจำนวนและส่งเฉพาะผลลัพธ์ที่เป็นจำนวนเต็มเดี่ยวกลับไปยังแอปของคุณ ประหยัดทั้งการอ่านเอกสารที่เรียกเก็บเงินและการถ่ายโอนไบต์ เมื่อเทียบกับการดำเนินการค้นหาแบบเต็ม

แบบสอบถามการรวมขึ้นอยู่กับการกำหนดค่าดัชนีที่มีอยู่ซึ่งแบบสอบถามของคุณใช้อยู่แล้ว และปรับขนาดตามสัดส่วนของจำนวนรายการดัชนีที่สแกน ซึ่งหมายความว่าการรวมชุดข้อมูลขนาดเล็กถึงขนาดกลางจะดำเนินการภายใน 20-40 มิลลิวินาที แม้ว่าเวลาแฝงจะเพิ่มขึ้นตามจำนวนรายการที่นับ

ใช้การรวม count()

อ้างถึงข้อมูลตัวอย่างที่เราตั้งค่าไว้ใน การรับข้อมูล

การรวม count() ต่อไปนี้จะส่งคืนจำนวนเมืองทั้งหมดในการรวบรวม cities

Web version 9

const coll = collection(db, "cities");
const snapshot = await getCountFromServer(coll);
console.log('count: ', snapshot.data().count);
สวิฟต์
หมายเหตุ: ผลิตภัณฑ์นี้ไม่พร้อมใช้งานบนเป้าหมาย watchOS และ App Clip
let query = db.collection("cities")
let countQuery = query.count
do {
    let snapshot = try await countQuery.getAggregation(source: .server)
    print(snapshot.count)
} catch {
    print(error);
}
วัตถุประสงค์-C
หมายเหตุ: ผลิตภัณฑ์นี้ไม่พร้อมใช้งานบนเป้าหมาย watchOS และ App Clip
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())
    }
}

Dart

// Returns number of documents in users collection
db.collection("users").count().get().then(
      (res) => print(res.count),
      onError: (e) => print("Error completing: $e"),
    );
ชวา
CollectionReference collection = db.collection("cities");
AggregateQuerySnapshot snapshot = collection.count().get().get();
System.out.println("Count: " + snapshot.getCount());
      
โหนด js
const collectionRef = db.collection('cities');
const snapshot = await collectionRef.count().get();
console.log(snapshot.data().count);
      

การรวม count() คำนึงถึงตัวกรองใด ๆ ในแบบสอบถามและคำสั่ง limit ใด ๆ ตัวอย่างเช่น การรวมต่อไปนี้ส่งคืนจำนวนเมืองที่ state เท่ากับ CA

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);
สวิฟต์
หมายเหตุ: ผลิตภัณฑ์นี้ไม่พร้อมใช้งานบนเป้าหมาย watchOS และ App Clip
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);
}
วัตถุประสงค์-C
หมายเหตุ: ผลิตภัณฑ์นี้ไม่พร้อมใช้งานบนเป้าหมาย watchOS และ App Clip
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())
    }
}

Dart

// This also works with collectionGroup queries.
db.collection("users").where("age", isGreaterThan: 10).count().get().then(
      (res) => print(res.count),
      onError: (e) => print("Error completing: $e"),
    );
ชวา
CollectionReference collection = db.collection("cities");
Query query = collection.whereEqualTo("state", "CA");
AggregateQuerySnapshot snapshot = query.count().get().get();
System.out.println("Count: " + snapshot.getCount());
      
โหนด 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 ทำงานเหมือนกันกับการค้นหาการรวม count() เช่นเดียวกับการค้นหาปกติที่ส่งคืนเอกสาร กล่าวอีกนัยหนึ่ง ถ้ากฎของคุณอนุญาตให้ไคลเอ็นต์ดำเนินการค้นหาคอลเล็กชันหรือกลุ่มคอลเล็กชันบางรายการได้ ไคลเอ็นต์ยังสามารถดำเนินการรวม count() ในการค้นหาเหล่านั้นได้ด้วย เรียนรู้เพิ่มเติมเกี่ยวกับ วิธีที่กฎความปลอดภัยของ Cloud Firestore โต้ตอบกับข้อความค้นหา

ข้อจำกัด

สังเกตข้อจำกัดต่อไปนี้ในแบบสอบถามการรวม count() :

  • การค้นหาการรวม count() ได้รับการสนับสนุนผ่านการตอบสนองของเซิร์ฟเวอร์โดยตรงเท่านั้น ข้อความค้นหาให้บริการโดยแบ็กเอนด์ Cloud Firestore เท่านั้น โดยข้ามแคชในเครื่องและการอัปเดตที่บัฟเฟอร์ใดๆ ลักษณะการทำงานนี้เหมือนกันกับการดำเนินการภายใน ธุรกรรม Cloud Firestore ขณะนี้คุณไม่สามารถใช้ข้อความค้นหา count() กับผู้ฟังแบบเรียลไทม์และข้อความค้นหาออฟไลน์ได้

  • หากการรวม count() ไม่สามารถแก้ไขได้ภายใน 60 วินาที ระบบจะส่งกลับข้อผิดพลาด DEADLINE_EXCEEDED ประสิทธิภาพขึ้นอยู่กับการกำหนดค่าดัชนีของคุณและขนาดของชุดข้อมูล

    หากไม่สามารถดำเนินการให้เสร็จสิ้นภายในกำหนดเวลา 60 วินาที วิธีแก้ไขที่เป็นไปได้คือการใช้ ตัวนับ สำหรับชุดข้อมูลขนาดใหญ่

  • การรวม count() อ่านจากรายการดัชนีและนับเฉพาะฟิลด์ที่จัดทำดัชนี

  • การเพิ่มส่วนคำสั่ง OrderBy ในแบบสอบถามจะจำกัดจำนวนเอกสารที่มีฟิลด์การเรียงลำดับอยู่

ราคา

ราคาสำหรับ count() ขึ้นอยู่กับจำนวนของรายการดัชนีที่ตรงกับข้อความค้นหา คุณจะถูกเรียกเก็บเงินจำนวนเล็กน้อยสำหรับการอ่านข้อมูลที่ตรงกันจำนวนมาก

ดู ข้อมูลราคา โดยละเอียดเพิ่มเติม