Replace with

설명:

기존 문서의 필드를 지정된 표현식의 필드로 바꿉니다. 표현식은 리터럴 맵이거나 맵으로 평가되는 표현식일 수 있습니다. 지정된 표현식이 맵으로 평가되지 않으면 이 단계에서 오류가 반환됩니다.

구문:

Mode: {full_replace | merge_overwrite_existing | merge_keep_existing}

replace_with(map: Expr, mode: Mode)

모드 동작:

  • 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();
    
자바
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"}