說明
將現有文件中的欄位替換為指定運算式中的欄位。
運算式可以是常值對應,也可以是評估為對應的運算式。如果指定運算式未評估為對應,這個階段會傳回錯誤。
支援 3 種模式:
full_replace:將整份文件替換為指定運算式的結果,並省略未出現在運算式中的欄位。merge_overwrite_existing:將運算式與現有文件合併,並以運算式中的值覆寫文件中的欄位值merge_keep_existing:將運算式與現有文件合併,只有在文件中不存在欄位值時,才會新增欄位值。
範例
建立 cities 集合,並加入下列文件:
Node.js
await db.collection("cities").doc("SF").set({name: "San Francisco", population: 800000, location: {country: "USA", state: "California"}});
await db.collection("cities").doc("TO").set({name: "Toronto", population: 3000000, province: "ON", location: {country: "Canada", province: "Ontario"}});
await db.collection("cities").doc("NY").set({name: "New York", location: {country: "USA", state: "New York"}});
await db.collection("cities").cov("AT").set({name: "Atlantis", population: null});
使用 full_replace 模式取得文件的變異版本
擷取巢狀 location 欄位,捨棄所有其他資料:
Node.js
const names = await db.pipeline() .collection("/cities") .replace_with(Field.of("location"), "full_replace") .execute();
Java
Pipeline.Snapshot names = firestore.pipeline().collection("cities").replaceWith(field("location")).execute().get();
Go
snapshot := client.Pipeline(). Collection("cities"). ReplaceWith(firestore.FieldOf("location")). Execute(ctx)
這會產生以下文件:
{ country: "USA", state: "California" },
{ country: "Canada", province: "Ontario" },
{ country: "USA", state: "New York" },
{ }
使用 merge_overwrite_existing 模式設定欄位
將所有文件的 population 欄位設為 0,覆寫現有值:
Node.js
const censoredResults = await db.pipeline() .collection("/cities") .replace_with(map("population", 0), "merge_overwrite_existing") .execute();
這會產生以下文件:
{name: "San Francisco", population: 0, location: {country: "USA", state: "California"}},
{name: "Toronto", population: 0, province: "ON", location: {country: "Canada", province: "Ontario"}},
{name: "New York", population: 0, location: {country: "USA", state: "New York"}},
{name: "Atlantis", population: 0}
使用 merge_keep_existing 模式新增預設值
為未出現在文件中的 location 設定預設值:
Node.js
const defaultedResults = await db.pipeline() .collection("/cities") .replace_with(map("location", "unknown"), "merge_keep_existing") .execute();
這會產生以下文件:
{ name: "San Francisco", population: 800000, location: { country: "USA", state: "California" } },
{ name: "Toronto", province: "ON", population: 3000000, location: { country: "Canada", province: "Ontario" } },
{ name: "New York", location: { country: "USA", state: "New York" } },
{ name: "Atlantis", population: null, location: "unknown" }