Firestore查询单个文档 [英] Firestore query single document
问题描述
在flutter应用中,仅当最后更新的字段大于本地最后更新的字段时,才需要从firestore中拉出用户文档.
In a flutter app, I need to pull the users document from firestore only if the last updated field is greater then the last updated locally.
目前这是我要做的:
QuerySnapshot usersData = await Firestore.instance
.collection("users")
.where("lastUpdated", isGreaterThan: lastUpdatedLocally)
.where("userId", isEqualTo: userId)
.getDocuments();
Map<String, dynamic> userData =
usersData.documents.isEmpty ? {} : usersData.documents.first.data;
我有三个问题:
- 是否可以在单个文档的
get
查询中执行类似的操作,而知道文档ID是用户ID,查询整个集合似乎并不正确. li> - 如果没有,我们是否可以通过文档ID进行查询,例如:
.where(< documentId> ;, isEqualTo:userId)
,而不是在名为"userId"的文档中进行归档;. - 最后,执行我在此所做的然后再查询单个文档(如果可能)的速度是否较慢.
- Is it possible to do something like this in a
get
query for a single document, it doesn't seem right to query the whole collection knowing that the document id is the user id. - If not, can we do a query by the document id, something like:
.where(<documentId>, isEqualTo: userId)
instead of having a filed in the document called "userId". - And lastly, is it slower to do what I did here then to query a single document (if it is possible).
推荐答案
如果您知道文档ID,则可以肯定地 DocumentReference 而不是构建查询.
If you know the document ID, you can certainly get() a single document using a DocumentReference instead of building a Query.
DocumentSnapshot snapshot = await Firestore.instance.collection("users").document(userId).get()
性能差异可以忽略不计.Firestore查询全部基于检索到的文档总数而不是集合中的文档数执行.像上面的文档get()本质上与使用
The performance difference is negligible. Firestore queries all perform based on the total number of documents retrieved, not the number of documents in the collection. A document get() like above is essentially the same as if you were to do a query on the document ID field using FieldPath.documentId as the name of the field.
如果仅在特定字段匹配的情况下尝试获取文档,则必须使用 FieldPath.documentId
进行完整查询.但是,即使是不匹配任何文档的查询,仍然会花费您一读.
If you're trying to get the document only if a certain field matches, you will have to do a full query with FieldPath.documentId
. However, even a query that doesn't match any documents will still cost you a read.
这篇关于Firestore查询单个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!