是否可以使用新的Firebase数据库Cloud Firestore来计算一个集合有多少项?
如果是,我该怎么做?
是否可以使用新的Firebase数据库Cloud Firestore来计算一个集合有多少项?
如果是,我该怎么做?
当前回答
使用带有偏移量和限制的分页的解决方案:
public int collectionCount(String collection) {
Integer page = 0;
List<QueryDocumentSnapshot> snaps = new ArrayList<>();
findDocsByPage(collection, page, snaps);
return snaps.size();
}
public void findDocsByPage(String collection, Integer page,
List<QueryDocumentSnapshot> snaps) {
try {
Integer limit = 26000;
FieldPath[] selectedFields = new FieldPath[] { FieldPath.of("id") };
List<QueryDocumentSnapshot> snapshotPage;
snapshotPage = fireStore()
.collection(collection)
.select(selectedFields)
.offset(page * limit)
.limit(limit)
.get().get().getDocuments();
if (snapshotPage.size() > 0) {
snaps.addAll(snapshotPage);
page++;
findDocsByPage(collection, page, snaps);
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
findDocsPage是一个递归方法,用于查找集合的所有页面 selectedFields用于优化查询,只获得id字段而不是整个文档 限制每个查询页面的最大大小 页面定义用于分页的初始页面
从我做的测试来看,它可以很好地收集大约120k条记录!
其他回答
截至2022年10月,Firestore在客户端sdk上引入了count()方法。现在您可以在没有下载的情况下计算查询。
对于1000份文件,它将收取你阅读1份文件的费用。
网络(v9)
Firebase 9.11.0介绍:
const collectionRef = collection(db, "cities");
const snapshot = await getCountFromServer(collectionRef);
console.log('count: ', snapshot.data().count);
Web V8
不可用。
节点(管理)
const collectionRef = db.collection('cities');
const snapshot = await collectionRef.count().get();
console.log(snapshot.data().count);
Android (Kotlin)
在firestore v24.4.0 (BoM 31.0.0)引入:
val query = db.collection("cities")
val countQuery = query.count()
countQuery.get(AggregateSource.SERVER).addOnCompleteListener { task ->
if (task.isSuccessful) {
val snapshot = task.result
Log.d(TAG, "Count: ${snapshot.count}")
} else {
Log.d(TAG, "Count failed: ", task.getException())
}
}
苹果平台(Swift)
Firestore v10.0.0引入:
do {
let query = db.collection("cities")
let countQuery = query.countAggregateQuery
let snapshot = try await countQuery.aggregation(source: AggregateSource.server)
print(snapshot.count)
} catch {
print(error)
}
在2020年,Firebase SDK中还没有这个功能,但Firebase扩展(Beta)中有,不过设置和使用起来相当复杂……
合理的方法
帮手……(创建/删除似乎是多余的,但比onUpdate便宜)
export const onCreateCounter = () => async (
change,
context
) => {
const collectionPath = change.ref.parent.path;
const statsDoc = db.doc("counters/" + collectionPath);
const countDoc = {};
countDoc["count"] = admin.firestore.FieldValue.increment(1);
await statsDoc.set(countDoc, { merge: true });
};
export const onDeleteCounter = () => async (
change,
context
) => {
const collectionPath = change.ref.parent.path;
const statsDoc = db.doc("counters/" + collectionPath);
const countDoc = {};
countDoc["count"] = admin.firestore.FieldValue.increment(-1);
await statsDoc.set(countDoc, { merge: true });
};
export interface CounterPath {
watch: string;
name: string;
}
出口消防钩
export const Counters: CounterPath[] = [
{
name: "count_buildings",
watch: "buildings/{id2}"
},
{
name: "count_buildings_subcollections",
watch: "buildings/{id2}/{id3}/{id4}"
}
];
Counters.forEach(item => {
exports[item.name + '_create'] = functions.firestore
.document(item.watch)
.onCreate(onCreateCounter());
exports[item.name + '_delete'] = functions.firestore
.document(item.watch)
.onDelete(onDeleteCounter());
});
在行动
将跟踪构建根集合和所有子集合。
在/counters/ root路径下
现在收集计数将自动更新,最终!如果需要计数,只需使用收集路径并在其前面加上计数器即可。
const collectionPath = 'buildings/138faicnjasjoa89/buildingContacts';
const collectionCount = await db
.doc('counters/' + collectionPath)
.get()
.then(snap => snap.get('count'));
限制
由于此方法使用单个数据库和文档,因此每个计数器的Firestore约束为每秒更新1次。它最终将是一致的,但在添加/删除大量文档的情况下,计数器将落后于实际收集计数。
Firebase/Firestore中的新功能提供了集合中的文档计数:
请参阅本线程以了解如何实现它,并提供了一个示例。
如何计算在一个集合中的Firebase Firestore与WHERE查询在react.js文档的数量
其中一个快速省钱的技巧是:-
创建一个文档并在firestore中存储一个“count”变量,当用户在集合中添加新文档时,增加该变量,当用户删除一个文档时,减少变量。如。 updateDoc(doc(db, "Count_collection", "Count_Doc"), {count: increment(1)});
注:计数用(-1)递减,用(1)递增
如何节省金钱和时间:-
你(firebase)不需要循环通过集合,浏览器也不需要加载整个集合来计数文档的数量。 所有的计数都保存在一个名为“count”或其他变量的文档中,因此使用不到1kb的数据,并且它只在firebase firestore中使用1次读取。
FireStore现在支持该功能,尽管是Beta版。 下面是Firebase的官方文档