我想创建一个名为question_count的字段值,我想增加该值并将其添加到我的Cloud Firestore文档中。我已经尝试过:
document_reference.update("question_count", FieldValue.increment(1))
问题:我必须手动将question_count字段添加到我的Cloud Firestore文档中,然后上面的代码将使该值递增。Cloud Firestore Dashboard我想要的:有人告诉我,如果在Cloud Firestore中尚未使用指定的字段值使用DocumentReference update(...),则会创建该字段值。那是一个错误的假设吗?
update
方法仅在文档已存在时才有效。如果要执行写操作,即任一创建文档或在已有文档时对其进行更新,请使用docRef.set(..., SetOptions.merge())
。
因此,在您的情况下,类似:
// Update one field, creating the document if it does not already exist.
Map<String, Object> data = new HashMap<>();
data.put("question_count", FieldValue.increment(1));
document_reference.set(data, SetOptions.merge());
另请参阅writing data上的文档。