TransWikia.com

Firestore query single document

Stack Overflow Asked by Zvi Karp on December 20, 2020

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

2 Answers

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.

Correct answer by Doug Stevenson on December 20, 2020

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"));
});

Answered by Neoflies on December 20, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP