编辑Firestore集合组查询文档

时间:2020-07-16 12:45:20

标签: android firebase google-cloud-firestore

我想知道是否可以通过collectionGroup查询更新文档的字段。我已经按如下所示设置了查询,我想在查询返回的文档中.update()一个字段。

Query query = db.collectionGroup("orders").whereEqualTo("restaurantid",fAuth.getUid()).whereEqualTo(docId,getId());

        query.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
            @Override
            public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                if (!queryDocumentSnapshots.isEmpty()){
                    Order order = queryDocumentSnapshots.getDocuments().get(0).toObject(Order.class);
                    //can i update the document here?


                }else
                {
                        Log.d("STATUS ERROR", "QUERY IS EMPTY");
                }

            }
        });

2 个答案:

答案 0 :(得分:2)

要在Firestore中写文档,您需要DocumentReference。您的queryDocumentSnapshots.getDocuments().get(0)给您一个DocumentSnapshot,其中有一个getReference method。所以:

Query query = db.collectionGroup("orders").whereEqualTo("restaurantid",fAuth.getUid()).whereEqualTo(docId,getId());

query.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
    @Override
    public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
        if (!queryDocumentSnapshots.isEmpty()){
            DocumentSnapshot snapshot = queryDocumentSnapshots.getDocuments().get(0);

            // Order order = snapshot.toObject(Order.class);

            DocumentReference ref = snapshot.getReference();

            ref.update("fieldName", "value");

        } else {
            Log.d("STATUS ERROR", "QUERY IS EMPTY");
        }
    }
});

答案 1 :(得分:0)

您可以使用其引用和update方法来更新任何文档的值。

DocumentReference washingtonRef = db.collection("cities").document("DC");
washingtonRef.update(key, value);