How to search array and find user ID in Firestore - android

Firstly, I am sorry for my terrible english.
I am trying to learn and make a Firestore app. In my app, I get the colors of users. If other users chosen the same color, it matches the users. It is very simple app but I cant write the query and get userId.
My database example:
cRef = fStore.collection("Users");
cRef.whereArrayContains("colors", "red").get();
I have read many articles but could not understand, how can I list the UserId's with this 'whereArrayContains()' method? Thank you for your helpings.

You should indeed use the array-contains operator to filter based on array values.
In your case you would do something along these lines:
cRef = fStore.collection("Users");
cRef.whereArrayContains("colors", "red")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
More details in the doc here and here.

Related

FireStore How can i get Collection in an order (Dess / Accen )

i have a collecntion Which Contain Multiple document and i want to fetch higest index document form it
I want to fetch Lat document of Customer_Info
but i dont know it value
and i dont know how to implement orderBy in collections => Document => document_Data
If Bill_ID is same as the document ID, you can use orderBy() and limit(1) to get last document in that collection as shown below:
db.collection("(?)/Business/Customer_Info")
.orderBy("Bill_ID", Direction.DESCENDING)
.limit(1)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
However, you must ensure the field must be a number or the order will not be correct as Firestore orders them lexicographically.
You should avoid using sequential documents IDs and using a timestamp to order documents might be a better idea.
Also checkout:
Limitations of using sequential IDs in Cloud Firestore.
Order and limit data with Cloud Firestore

How to query firestore for documents with a timestamp field?

I want to fetch all documents whose START_DATE is within last 10 days.
For example, if today is 17-04-2020(DD-MM-YYYY) then I want to fetch documents which have START_DATE 7-04-2020 or above
My Collection structure looks like this:
I need to do this for my android app in Java.
If you want to query a timestamp field in a collection, you can use either a java Date or Firestore Timestamp object with a range filter.
db
.collection("POLL")
.whereGreaterThan("START_DATE", date1)
.whereLessThan("START_DATE", date2)
You will have to provide the values for date1 and date2 that meet your needs.
I think you have not read the documents, please check this once you will get the solution:
https://firebase.google.com/docs/firestore/query-data/queries
Use where query with condition according to your requirement.
Ex:
db.collection("cities")
.whereEqualTo("capital", true)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
})
;
EDIT
https://maye.pwafire.org/articles/using-timestamp-to-filter-and-order-firebase-cloud-firestore-documents/

Firestore query returns empty JSON object

We are developing a mobile application where are using firebase as backend. We are using cloud firestore as our database. While querying data from Android it return blank JSON. Here is how our database looks
Here is our android code
db.collection("meta_data")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
It prints
college_metadata => {}
Your "college_metadata" document doesn't actually contain any fields. It's what I would call an "empty document". If you print the data from an empty document, you will get an empty map, which is what you're seeing in your output: {}.
Queries in Firestore are "shallow", which means they don't fetch nested subcollections of matched documents. If you want the data in a nested subcollection, you will have to query for it by name:
db
.collection("meta_data")
.document("college_metadata")
.collection("course")
.get()
This will give you all the documents in the "course" subcollection of the empty document named "college_metadata".
There is no way to make a Firestore query get all nested documents in all nested collections. You need to write that code, if that's what you want.

How to query by type and date?

I cant get user recipe Ids to list
I try to query by whereEqualTo and orderBy but on compile firebase suggested me to create indexing, so I did that but it dont give me any results.
for (String mealType : dishTypeList){
userCollectionReference.document(userId).collection("favourites")
.whereEqualTo("mealType", mealType)
.orderBy("dateWhenSetFavourite", Query.Direction.DESCENDING)
.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
List<String> favouriteRecipeIds = new ArrayList<>();
for (QueryDocumentSnapshot document : task.getResult()){
favouriteRecipeIds.add(document.toObject(FavouriteRecipeModel.class).getRecipeId());
Log.d(TAG, "LIST LIST: " + favouriteRecipeIds);
}
myFirebaseCallBack.onSuccessCallback(favouriteRecipeIds);
}
});
}
I want to get recipeId whereEqualTo by mealType and ordered by dateWhenSetToFavourites
This is my database:
Are you sure that dishTypeList contains the same dish types that are used in the database? If yes, your code looks fine to me. If all your objects in the database contain the recipe id than the following code should work:
favouriteRecipeIds.add(document.toObject(FavouriteRecipeModel.class).getRecipeId());
Otherwise, a more simpler way of getting the document id would be:
favouriteRecipeIds.add(document.getId());
Beside that, everytime you are getting as a result a Task object, check to see if it is successful:
if (task.isSuccessful()) {
//Your logic
} else {
Log.d(TAG, task.getException().getMessage());
}
And also use the else part of the statement to check for an error message.

SELECT where document field contains the string in Firestore?

How can I select a document in my Firestore where the value of a field contains 'pp' ;
How to add option like whereContains("title","pp") in firestore ?
firestore added multiple where cause but we need "contains" also
to improve search. Is there any alternate method available or firestore developers ignore it?
FirebaseFirestore db2 = FirebaseFirestore.getInstance();
db2.collection("products")
.whereEqualTo("cat","fruits")
.whereEqualTo("subcat","apple")
.whereEqualTo("blocked",false)
.whereContains("title","pp")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for(int i=0;i<task.getResult().size();i++){
Product product=task.getResult().getDocuments().get(i).toObject(Product.class);
Log.d(TAG+"2", product.getTitle()+"");
}
for (QueryDocumentSnapshot document : task.getResult()) {
// Log.d(TAG+"2", document.getId() + " => " + document.getData());
}
} else {
Log.w(TAG+"2", "Error getting documents.", task.getException());
}
}
});
Firestore has no method to search by substring. Your options are to mirror your data to a full text search engine such as Algolia, be clever about how you structure your data to support the specific kinds of queries that are similar to a substring search, or file a feature request.

Categories

Resources