对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
See how MongoDB 9.0 delivers up to 2x higher throughput.
MongoDB Branding Shape
Register now >
Docs 菜单

$mergeObjects (表达式)

$mergeObjects

将文档大量合并为单个文档。

注意

消歧

本页介绍了用作表达式的 $mergeObjects,该表达式可合并文档大量。

您还可以使用 $mergeObjects (accumulator),它返回一群组输入文档的合并文档。

用作表达式时,$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 会使用 tomatoes.critic 评级覆盖 imdb 评级。每个子文档的唯一字段会保留在结果中。

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 从已存在 imdb.rating 和 tomatoes.critic.rating 的 2010 中筛选动作片。

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

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

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

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

    • imdb 中的唯一字段 votes 和 id 以及 tomatoes.critic 中的 numReviews 和 meter 均会保留。

给本页内容打分