如何查询集合以获取特定文档? [英] How to query a collection to get specific documents?

查看:47
本文介绍了如何查询集合以获取特定文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将通过一个示例开始解释我的问题,我有两个名为Users and Foods的根集合.在用户"集合中,包含带有用户信息(例如名称,图像和年龄)的文档.在foodsCollection中,包含带有食物名称",成分"和图像"等字段的文档.现在,我想让用户按用户的意愿为食物添加书签.因此,我在名为Bookmark的用户文档中创建了另一个集合,并将 Food文档的ID 保存在Bookmark集合的文档中.现在,我想使用保存的食品文档ID获得唯一的带有书签的文档.我将写数据结构以进一步理解.

I'll start to explain my issue using an example, I have 2 root collections named Users and Foods. In Users collection, contains documents with User information such as Name, Image, and Age. In foodsCollection, contains documents with Fields such as Food_name, Ingredients, and Image. Now I want to let the users bookmark foods as user wish.Therefore I create one more collection in a user document named Bookmark and saved the Food document's Id in the Bookmark collection's documents. Now I want to get the only Bookmarked Document using saved food document Ids. I ll write my data structure for further understanding.

 Foods(Collection) ----1ztEzZLkTp5XOZzsoYRL(Feilds--Name,Image,Ingradents,Document_Id)
                 
                  ----4Q6k0MifwEyoLs8rgZbs(Feilds--Name,Image,Ingradents,Document_Id)
                
                  ----870BEaDFMkMWTi4VaXmh(Feilds--Name,Image,Ingradents,Document_Id)
                  [...]


 Users(Collection)----User1(Document)----Bookmarks(Collection)----RandomId("Bookmarked_Doc_Id" - 1ztEzZLkTp5XOZzsoYRL)
                                                              ----RandomId("Bookmarked_Doc_Id" - 870BEaDFMkMWTi4VaXmh)
    
                  ----User2(Document)----Bookmarks(Collection)----RandomId("Bookmarked_Doc_Id" - 1ztEzZLkTp5XOZzsoYRL)
    
                  [...]

现在我想使用Bookmarked_Doc_Id获取Food Collection的文档数据

Now I want to get the Food collection's document data using Bookmarked_Doc_Id

例如,当User1单击书签"选项卡时,他可以看到2个具有名称,图像和渐变的书签.

For example, When User1 clicks bookmark tab, he can see 2 bookmarks with its name,image and ingradents.

如何归档?

 rootRef.collection("Users").document(USER_ID).collection("Bookmarks").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()){
                    for (DocumentSnapshot document : task.getResult()){
                        if (document.exists()){
                            String getDocuments = document.get("Bookmark_Document_Id").toString();
                            loadBookmarks(getDocuments);
                            Log.d(TAG, "onComplete: "+" "+getDocuments);
                        }
                    }
                }
            }
        });
  private void loadBookmarks(String getDocuments) {
    Query query = FirebaseFirestore.getInstance().collection("Foods").whereEqualTo("Document_Id",getDocuments);
    PagedList.Config config = new PagedList.Config.Builder()
            .setEnablePlaceholders(false)
            .setPrefetchDistance(2)
            .setInitialLoadSizeHint(2)
            .setPageSize(3)
            .build();

    FirestorePagingOptions<FoodItems> options = new FirestorePagingOptions.Builder<FoodItems>()
            .setQuery(query, config, FoodItems.class)
            .build();

    food_items_recycle_adapter = new Food_Items_Recycle_Adapter(options, progressIndicator,null);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    recyclerView.setAdapter(food_items_recycle_adapter);
    food_items_recycle_adapter.notifyDataSetChanged();
    food_items_recycle_adapter.startListening();
}

此代码仅向我显示最新添加的书签,而不显示所有书签.

This code only shows me the latest added bookmark instead of showing all bookmarks.

推荐答案

最后,我解决了我的问题,这就是我想要的:)

Finally, I solve my problem and this is what I wanted :)

enter code here  final FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    if (user!=null){
        String USER_ID = user.getUid();

        rootRef.collection("Users").document(USER_ID).collection("Bookmarks")
                .addSnapshotListener(new EventListener<QuerySnapshot>() {
                    @Override
                    public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
                        if (error!=null){
                            Log.w(TAG, "Listen failed.", error);
                            return;
                        }
                        List<String> foodlist = new ArrayList<>();
                        assert value != null;
                        for (QueryDocumentSnapshot doc : value) {
                            if (doc.get("Bookmark_Document_Id") != null) {


                                foodlist.add(doc.getString("Bookmark_Document_Id"));
                                Log.d(TAG, "Food items are: " + foodlist);
                               
                                Query query = rootRef.collection("Recipes").document("Food_Recipe").collection("Powder_Recipe").whereIn("Document_Id",foodlist);
                                PagedList.Config config = new PagedList.Config.Builder()
                                        .setEnablePlaceholders(false)
                                        .setPrefetchDistance(2)
                                        .setInitialLoadSizeHint(2)
                                        .setPageSize(3)
                                        .build();

                                FirestorePagingOptions<FoodItems> options = new FirestorePagingOptions.Builder<FoodItems>()
                                        .setQuery(query, config, FoodItems.class)
                                        .build();

                                food_items_recycle_adapter = new Food_Items_Recycle_Adapter(options, progressIndicator,null);
                                recyclerView.setHasFixedSize(true);
                                recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
                                recyclerView.setAdapter(food_items_recycle_adapter);
                                food_items_recycle_adapter.notifyDataSetChanged();
                                food_items_recycle_adapter.startListening();

                            }else {
                                Log.d(TAG, "onEvent: this is nulll");
                            }


                        }
                    }
                });
    }

谢谢 @s_o_m_m_y_e_e ,您试图解决我的问题.应该有很多方法可以对此进行存档,但这可以按我的意愿进行工作.

Thank you @s_o_m_m_y_e_e, you tried to solve my issue. There are should be many ways to archive this, but this is working as I wanted.

这篇关于如何查询集合以获取特定文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆