简体   繁体   中英

Query and algorithms using firestore db?

I am currently trying to figure out how to match and/or compare data in firestore database. Lets say I have 10 apples. My apple has the color red. I want to be able to compare my color to the other 10 apples and then match only with the ones who has the color red (there are 2 apples with the color red). How can I achieve this while using firestore database as the main database for all apples?

Firebase Db looks something like this:

在此处输入图像描述

apple1 is red and should match with apple5. The rest are different colors. When the user press the search button, it should filter the firestore Db and only match with the adequate respons (in this case apple5 which is also red) How can I achieve this? Do I need to use a third party library to create this algorithm or can it be done in kotlin since it is to my understanding that some features does not work with firestore Db? Appreciate any feedback!

That's a pretty straightforward query, 'fetch documents where the value of field color is red '. Try:

db.collection("apples")
        .whereEqualTo("color", "red")
        .get()
        .addOnSuccessListener { documents ->
            for (document in documents) {
                Log.d(TAG, "${document.id} => ${document.data}")
            }
        }
        .addOnFailureListener { exception ->
            Log.w(TAG, "Error getting documents: ", exception)
        }

Checkout the documentation for more query examples that Firestore supports.

Basically, you can use Queries to match a certain condition and get all documents.

For your case, you can use the following code snippet to get the data based on color

try {
AsyncSnapshot<QuerySnapshot> data = firestore.collection("hubs")
                                    .where("color", isEqualTo: "red")
                                    .get();
final docs = data.data!.docs; 

docs.forEach((e)=>{
    //each firestore document
});
}

Find the official documentation here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM