Firestore query single document

给你一囗甜甜゛ 提交于 2021-02-11 14:22:43

问题


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.

Currently this is what I do:

    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;

I have three questions:

  1. 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.
  2. 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".
  3. And lastly, is it slower to do what I did here then to query a single document (if it is possible).

回答1:


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()

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.

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.




回答2:


You can specify document ID when calling Firestore like this

var document = await Firestore.instance.collection('COLLECTION_NAME').document('TESTID1');
document.get() => then(function(document) {
  print(document("name"));
});


来源:https://stackoverflow.com/questions/63096011/firestore-query-single-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!