Composite query with Orderby in firebase cloud function - firebase

is this a valid query for Firestore?
return firestore.collection('users')
.where('userInfo.gender', '==', "male")
.where('userInfo.yob','>=',`${data.minYear}`)
.where('userInfo.yob','<=',`${data.maxYear}`)
.orderBy('count','asc')
.limit(5)
.get()
if i want this query to be valid how do i need to structure this?
or how do i add the indexes?

It is not. If you're doing a greater-than-or-less-than search on one field, you can't then order your results by another field. You're going to have to do the yob query first, and then sort the results afterwards.
For more information, you can check out the documentation here, or this helpful video!

Related

Flutter Firebase whereQuery in collectionGroup

Why I cant use whereQuery in collectionGroup.
When I use whereQuery like that;
Query colRef = _firestore.collection("users");
colRef = colRef.where("name", isEqualTo: widget.name);
Its working, but when I use whereQuery like that;
Query colRef = _firestore.collectionGroup("users");
colRef = colRef.where("name", isEqualTo: widget.name);
Its not working, while geting the data, I query whether there is an error by using hasError and if else, and I get an error. and I must use collectionGroup while getting data from firebase.
Is there a solution to use whereQuery in collectionGroup?
Firestore Index Settings
I guess I need to somehow enable the disabled options here, but I don't know how to do it.
In summary I want all users in the application to have access to all kinds of data that I specify in the collection Group.
I need to set the composite and exemption part at the same time, when I set both parts according to the paths I want to query, the problem was solved.

How to make a query from a nested collection in firestore using flutter

I have a nested collection in firestore that I want to make a query from it.
As you can see the first collection called 'businessUsers' and the nested one called 'campaigns',
If I make a query for a field in the 'businessUsers' it's working OK:
return FirebaseFirestore.instance.collection("businessUsers").where('xxx',
isEqualTo:filterBusinessResult ).snapshots().map(_businessListFromSnapshot);
but how can I make a query to 'campaigns' collection field?
I tried
return FirebaseFirestore.instance.collection("businessUsers").doc().collection("campaigns").where('campaignCategory', isEqualTo:filterBusinessResult ).snapshots()
.map(_businessListFromSnapshot);
but it wont work.
Its important to note, that I need all the data with 'campaignCategory' == filterBusinessResult
any idea?
It depends on whether you want to query a specific user's campaigns, or the campaigns of all users together.
If you want to query the campaigns of a specific user, you need to query under their document:
FirebaseFirestore.instance
.collection("businessUsers").doc("your user ID").
.collection("campaigns")
.where('campaignCategory', isEqualTo:filterBusinessResult)
So you have to know the ID of the businessUsers document here.
If you want to query across all campaigns subcollections are once, that is known as a collection group query and would look like this:
FirebaseFirestore.instance
.collectionGroup("campaigns")
.where('campaignCategory', isEqualTo:filterBusinessResult)
The results are going to documents from the campaigns collection only, but you can look up the parent document reference for each DocumentSnapshot with docSnapshot.reference.parent.parent.
When querying something, .doc() requires the id of the document you're trying to get. So it's failing because it doesn't know which document in the businessUsers collection you're trying to fetch a subcollection on. You probably want to use a .collectionGroup() query here. They let you query all subcollections at once (see documentation here). With FlutterFire specifically, it's going to be something like:
var snapshots = FirebaseFirestore.instance.collectionGroup("campaigns")
.where("campaignCategory", isEqualTo: filterBusinessResult)
.snapshots();

Update document value in Firestore Cloud with Flutter, having only a unique key value of such document

I'm new to Cloud Firestore but already made some CRUD operations but now I'm really stuck with this thing.
Each document inside the 'tiposFrota' collection has a key 'nome:' with a unique value, no document will have the same value for the 'nome:' key.
The problem is, whenever the user adds another 'Truck' to some other collections I need to increment the value of 'qtde:' by one, and when they remove 'Truck' the program will increment the number by -1, working as a counter.
I managed to create an operation to update a key value, but only when you have the document id, but in this case the id is autogenerated because they may add or remove standard values from the 'tiposFrota' collection.
FirebaseFirestore.instance
.collection('controladores')
.doc('contadores')
.update({'numFrota': FieldValue.increment(1)}),
I'm really stuck with this, if anyone could please help.
Thanks!
Woah, managed to find a solution by myself, this post Get firestore collections based on values in array list in flutter.
Since the 'nome:' value is unique for each document inside the 'tiposFrota' collection I can use the .where statement as a filter for said document, get the snapshot with all the documents (but only getting one, obviously) and use the 'forEach' method to create a function using the '.id' parameter when calling the document.
FirebaseFirestore.instance
.collection('tiposFrota')
.where('nome', isEqualTo: carMake)
.get()
.then((querySnapshot) {
querySnapshot.docs.forEach((element) {
FirebaseFirestore.instance
.collection('tiposFrota')
.doc(element.id)
.update({
'qtde': FieldValue.increment(1)});
});
}),

how to query list of data on firestore?

I have a list. I need to check with field on firestore.
var ref = _db.collection('requirement')
.where('subCategory.id',arrayContains: ['8ZaGrU1kMGqxnYWBGO5R','UHtbfwoHOtdZ1rwlpjFE']);
this way is not working.
Possible with IN queries but i think the update will come late to flutter https://firebase.googleblog.com/2019/11/cloud-firestore-now-supports-in-queries.html?linkId=76644965
Updated:
https://pub.dev/packages/cloud_firestore#-changelog-tab-
0.12.11 #
Added support for in and array-contains-any query operators.

How to search document(s) from a collection based on a Field in Firestore database?

I'm working on a React Native application and I'm fetching profiles from a firebase collection.
And I want to add a search functionality where when I enter even the first 1 or 2 (or more) alphabets of a username and press the search button.
I should be able to fetch usernames starting with those 1 or 2 alphabets.
I did check Cloud Firestore queries but couldn't find one for my problem.
UPDATED QUESTION:
In the above code, I'm adding the below code as answered by Renaud Tarnec.
let queries = hashes.map(hash => rangeQueryParams(hash))
.map(range => profiles.where('hash', '>=', range.start).where('hash', '<', range.end)
.orderBy('displayName') // displayName is the name of Field here
.startAt(searchString)
.endAt(searchString + '\uf8ff')
.get());
But this doesn't seems to work. I guess it's because range filter and orderBy are on different fields here.
You should use a combination of orderBy(), startAt() and endAt(), see the documentation here: https://firebase.google.com/docs/firestore/query-data/order-limit-data?authuser=0
var searchString = 'Sh' //Example of value
firebase
.firestore()
.collection('yourCollectioName')
.orderBy('username')
.startAt(searchString)
.endAt(searchString + '\uf8ff')
.get()
.then(...)
The character \uf8ff used in the query is after most regular characters in Unicode, therefore the query matches all values that start with searchString.
An approach for full text search recommended by Firebase is to use Algolia https://firebase.google.com/docs/firestore/solutions/search
Using Firestore’s queries with start at and end at with an ordered collection certainly work. If you have a need for full text search within your app elsewhere that requires spelling tolerance etc for example then moving to Algolia is worth considering instead of using compound firestore queries

Resources