Query firebase docs by subcollection value - flutter

I have a Firebase Firestore DB with this structure:
Users (collection) -> user (doc) -> Reports (subcollection) -> report (doc) -> isHandled (bool field).
In my Flutter app, I want to query Users collection, and get only the user docs in which any of their reports collection docs is not handled (isHandled field == false).
I've tried to use Firestore's collectionGroup, but it returns only 1 report doc, instead of many user docs:
await FirebaseFirestore.instance
.collectionGroup('Reports')
.where(
'isHandled',
isEqualTo: false,
)
.get();
Does Firebase Firestore support any query of a collection by its docs' subcollection values?
Thank you very much in advance!

Does Firebase Firestore support any query of a collection by its docs' subcollection values?
No. When you query a collection or subcollection, it will only consider documents immediately within it. The data from a single collection's documents is managed by an "index" - queries only use that index to rapidly find data at scale.
Collection group queries are special in that they consider all collections with the same name, but they will still not consider nested subcollections.
You could perhaps combine a collection group query with further queries to get the "parent" user document from a matched report.

Related

Query Document to get snapshots from specific collections in Firestore in Flutter

I am using Firebase Cloud Firestore as the database for my app. The data structure is as below
expenses (collection)
|____[userId] (doc)
|___[year-month] collection
|___[expenseId] doc
|______expense fields(amount, date)
How can I get all expenses from a [userId] doc for specific [year-month] collections.
Is there a way to query a doc like we have .where for collection
You have nested collections in your database, right? you can simply chain collection and doc until you get the specific target, since it's not clear what is code variables and what is plain text names, I will assume that all documents and collections names are text, just to so you get the idea:
// This is the reference of a the "year-month" expenses of the user.
Query query = FirebaseFirestore.instance.collection('expenses').doc("userId").collection("year-month");
this will get you a QuerySnapshot containing all documents inside the collection with that "year-month" :
QuerySnapshot = await query.get()
You can also get a specific document in that collection like this:
DocumentReference doc = await query.doc("expenseId").get();

How to sort by a field in a sub-collection in firebase cloud firestore in flutter

I am trying to query a cloud firestore database and i need it to return all the documents in the chats collection sorted by the timestamp field which is a field that all the documents in the messages sub-collection have.
i tried writing a query like this.
FirebaseFirestore.instance.collection("chats").orderBy("messages.timestamp", descending: true)].get(),
but it does not return any documents when actually there are some documents there.
Firestore can only order or filter on data in the documents that it returns. There is no ability to order or filter on data outside of those documents.
So if we want to order chats in the timestamp of the last message in that chat (a common use-case), you'll have to include a lastMessageTimestamp field in the chat document itself, and update that whenever a message is written in its messages subcollection. With that lastMessageTimestamp field in place in each chats document, you can then order and filter on that.
Create a new collection called messages and store all messages for every user there (with a user id field). Reference the message uid's via an array in each chat. This way you can easily query for the messages associated with a chat session then sort them.

How to query latest documents first?

I am using Flutter & Cloud Firestore. I have a collection. There are many documents in that collection. My question is how to fetch those documents on the time basis. Like I want to firstly show those documents data that I had added latest and the oldest documents data at the last. How to do that?
Considering you have a timestamp field (named addedAt for example) in your documents, you can use the orderBy method .orderBy('addedAt', descending: true)

Firestore how to query documents chronologically

I understand that unlike Firebase Realtime DB, there isn't a built in method for querying Firestore documents chronologically.
Other than adding a timestamp field to each document, is there another elegant way to achieve that?
Apparently it isn't recommended to name documents in an ascending names (Do not use monotonically increasing document IDs)

flutter Issue in getting subcollection from document in firebase

I have an issue, I can't get subcollection from the document:
I have firestore db with
collection: collectionName
Inside collection documents and inside one document subcollection "items"
collectionName
Document1
Items <- subcollection
Item1
Item2
I use the following code but the items subcollection can't be retrieved from my db....`
```
QuerySnapshot snapshot = await Firestore.instance
.collection('collectionName')
.orderBy("order")
.getDocuments();
```
`then`
```
snapshot.documents.forEach((document) {})
```
The document doesn't have the items subcollection
You can not access a sub-collection like that. Last year, the team working at firestore released a new feature called the Collection Group. If you want to access the items collections try doing this:
Firestore.instance.collectionGroup('items')
This will contain all documents in the items sub-collection regardless of how deeply nested it is. Take a look at this for more information on collection groups.