对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

$mergeObjects (表达式)

$mergeObjects

将文档数组合并为单个文档。

注意

消歧

本页介绍了 $mergeObjects 当作为 表达式 使用时的情况,该表达式将合并一个文档数组。

您还可以在这些其他上下文中使用 $mergeObjects:

当作为表达式使用时,$mergeObjects 具有如下语法:

{ $mergeObjects: <expression> }

<expression> 操作数可以是:

  • 一个单一表达式,评估结果为要合并的文档数组。示例,$blogPosts,其中文档字段 blogPosts 包含文档数组。

  • 表达式数组,每个表达式都计算为一个文档。示例,[ "$doc1", "$doc2", "$doc3" ],其中每个文档字段包含单个文档。

$mergeObjects 忽略 null 输入值。如果所有输入值都是 null,$mergeObjects 将返回一个空文档 { }。

$mergeObjects 会在合并文档时覆盖字段值。如果多个输入文档包含相同的字段名,输出包含来自 最后一个包含冲突字段的输入文档的值。

例子
结果
{ $mergeObjects: [ { a: 1 }, null ] }
{ a: 1 }
{ $mergeObjects: [ null, null ] }
{ }
{ $mergeObjects: [ { a: 1 }, { a: 2, b: 2 }, { a: 3, c: 3 } ]}
{ a: 3, b: 2, c: 3 }
{ $mergeObjects: [ { a: 1 }, { a: 2, b: 2 }, { a: 3, b: null, c: 3 } ]}
{ a: 3, b: null, c: 3 }

本页上的示例使用来自 sample_mflix 数据集的数据。有关如何将此数据集加载到您的自管理 MongoDB 部署中的详细信息,请参阅 加载示例数据集。如果您对示例数据库进行了任何修改,您可能需要删除并重新创建数据库,才能运行此页面上的示例。

以下管道在 $replaceWith 中使用 $mergeObjects 将每部电影的 imdb 和 tomatoes.critic 子文档合并到单个 ratings 文档中。两个子文档都包含 rating 字段,因此 $mergeObjects 会使 imdb 评级被 tomatoes.critic 评级覆盖。来自每个子文档的独特字段将在结果中保留。

db.movies.aggregate( [ { $match: { genres: "Action", year: 2010, "imdb.rating": { $exists: true }, "tomatoes.critic.rating": { $exists: true } } }, { $sort: { title: 1 } }, { $limit: 5 }, { $replaceWith: { title: "$title", year: "$year", ratings: { $mergeObjects: [ "$imdb", "$tomatoes.critic" ] } } }] )

在前面的管道中:

  • $match 过滤器到来自 2010 的操作电影,具有现有 imdb.rating 和 tomatoes.critic.rating。

  • $sort 按 title 对文档进行字母顺序排序。

  • $limit 将输出限制为 5 个文档,以提高可读性。

  • $replaceWith 使用 $mergeObjects 来将 $imdb 和 $tomatoes.critic 合并到 ratings 字段中。

    • 因为两个子文档都包含 rating 字段,$mergeObjects 使用 tomatoes.critic 中的值(即最后一个参数)。

    • 来自 imdb 的唯一字段 votes 和 id,以及来自 tomatoes.critic 的 numReviews 和 meter,均得以保留。

给本页内容打分