说明:
将现有文档中的字段替换为给定表达式中的字段。该表达式可以是字面量映射,也可以是计算结果为映射的表达式。如果给定表达式的计算结果不是映射,此阶段会返回错误。
语法:
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();
这会生成以下文档:
{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"}