החלפה עם (שלב טרנספורמציה)
תיאור
הפונקציה מחליפה שדות במסמך הקיים בשדות בביטוי נתון.
הביטוי יכול להיות מפה מילולית או ביטוי שמוערך כמפה. אם ביטוי מסוים לא מוערך כמפה, השלב הזה מחזיר שגיאה.
יש 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();
המשך
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" }