取代為 (轉換階段)

說明

以指定運算式中的欄位取代現有文件中的欄位。

運算式可以是常值對映,也可以是求出值為對映的運算式。如果指定運算式評估結果不是對應,這個階段會傳回錯誤。

支援 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();

這會產生下列文件:

{ 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" }