Firestore 可以使用一个查询更新多个符合条件的文档吗? [英] Can Firestore update multiple documents matching a condition, using one query?

查看:18
本文介绍了Firestore 可以使用一个查询更新多个符合条件的文档吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

换句话说,我试图弄清楚在 SQL 中与此等效的 Firestore 是什么:

In other words, I'm trying to figure out what is the Firestore equivalent to this in SQL:

UPDATE table SET field = 'foo' WHERE <condition>`

是的,我在问如何更新多个文档一次,但与链接的问题,我专门询问如何一次性完成此操作,无需将任何内容读入内存,因为当您只想在所有与条件.

Yes, I am asking how to update multiple documents, at once, but unlike the linked questions, I'm specifically asking how to do this in one shot, without reading anything into memory, because there's no need to do so when all you want is to set a flag on all documents matching a condition.

db.collection('table')
  .where(...condition...)
  .update({
    field: 'foo',
  });

是我期望的工作,CollectionReference没有 .update 方法.

is what I expected to work, CollectionReference doesn't have an .update method.

事务和批量写入 文档提到了事务和批量写入.交易已结束,因为交易由任意数量的 get() 操作 和任意数量的写入操作组成"批量写入 也不是解决方案,因为它们逐个文档工作.

The Transactions and Batched Writes documentation mentions transactions and batched writes. Transactions are out because "A transaction consists of any number of get() operations followed by any number of write operations" Batched writes are also not a solution because they work document-by-document.

使用 MongoDB,这就是

db.table.update(
  { /* where clause */ },
  { $set: { field: 'foo' } }
)

那么,Firestore 是否可以像 SQL 数据库或 MongoDB 那样,通过一个查询更新多个文档,即不需要为每个文档往返客户端?如果没有,如何有效地做到这一点?

So, can Firestore update multiple documents with one query, the way SQL database or MongoDB work, i.e. without requiring a round-trip to the client for each document? If not, how can this be done efficiently?

推荐答案

在 Cloud Firestore 中更新文档需要知道其 ID.Cloud Firestore 不支持等效的 SQL 更新查询.

Updating a document in Cloud Firestore requires knowings its ID. Cloud Firestore does not support the equivalent of SQL's update queries.

您始终必须分两步执行此操作:

You will always have to do this in two steps:

  1. 使用您的条件运行查询以确定文档 ID
  2. 使用单个更新或一个或多个更新文档批量写入.

请注意,您只需要步骤 1 中的文档 ID.因此您可以运行仅返回 ID 的查询.这在客户端 SDK 中是不可能的,但可以通过 REST API 和管理 SDK 来完成,如下所示:如何获取 Cloud Firestore 集合中的文档 ID 列表?

Note that you only need the document ID from step 1. So you could run a query that only returns the IDs. This is not possible in the client-side SDKs, but can be done through the REST API and Admin SDKs as shown here: How to get a list of document IDs in a collection Cloud Firestore?

这篇关于Firestore 可以使用一个查询更新多个符合条件的文档吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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