简体   繁体   中英

search for sub-document value in firestore

I am using firestore database that has the following structure:

I have collection named NBDB , inside there are documents with the uid of each user. For example I have 2 users so I have 2 documents called: ZxK2BR... , xy9BHY... .

In each user document there is another collection called MyBooks and there are documents for all the books the user search.

Here are pictures from my database: 在此处输入图像描述

在此处输入图像描述 I want to make like home page screen that will disaply 20 random images from all of the images that users have in the app database.

From my understanding I need to get inside each user document and search for all the my books it has and then to move for the next user.

My finally goal is to read the BookID value of all of the users and to choose 20 random

I used the following to obtain all BookID from specific user:

FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference MyDB = db.collection( "NBDB" ).document(auth.getUid()).collection( "MyBooks" );

MyDB.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            List<String> list = new ArrayList<>();
            for (QueryDocumentSnapshot document : task.getResult()) {
                list.add(document.getString( "BookID" ));
            }
            Log.d(TAG, list.toString());
        } else {
            Log.d(TAG, "Error getting documents: ", task.getException());
        }
    }
});

Thank you

I think what you're looking to do is pull in 20 different images, at random, from any user's sub-collection. That said, if you don't choose to use another structure and wish to have all of the data nested, you can opt for a collectionGroup query.

The bit on "random" is a bit tricky, and you may want to use some hacky ways to make it work. But starting with getting access to the various user's nested sub collections:

All of this data, regardless of user, lives in collections called MyBooks so you can run a collectionGroup query on MyBooks .

The way I would do it, with the random-image hacky bit would be, in partial pseudocode code to give you an idea (I confirmed collectionGroups in the Java SDKs):

usedImages = []
for numbers 0 to 19 {
   let num = false
   while (!num) {
     let tempNum = Math.floor(Math.random() * 10);
     if (!( usedImages.includes(tempNum)){
        num = tempNum
     }
   }

   var allBooks = db.collectionGroup('MyBooks').where('imageKey', '==', num);
     allBooks.get().then(function (querySnapshot) {
        querySnapshot.forEach(function (doc) {
        console.log(doc.id, ' => ', doc.data());
     });
   });

}

The idea with the code is to generate 20 random and unique numbers num (probably better ways to do it than what I hacked together above), and then take that number and look for all entries in MyBooks where that imageKey exists. This is the hacky way around the random image code, where you would need to add a globally unique ID to each of them.

Collection Group doesn't specify a path of parent collections, so it allows you to look into all collections at once.

In the above pseudocode, you're running 20 collection groups queries.

You can find more on Collection Group queries here: https://firebase.google.com/docs/firestore/query-data/queries#collection-group-query

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