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

$replaceRoot(聚合阶段)

$replaceRoot

将输入文档替换为指定的文档。该操作会替换输入文档中的所有现有字段,包括 _id 字段。您可以将现有的嵌入式文档提升到顶层,或创建新文档进行提升(请参阅示例)。

注意

You can also use the $replaceWith stage. The $replaceWith stage peforms the same action as the $replaceRoot stage, but the stages have different forms.

The $replaceRoot stage has the following form:

{ $replaceRoot: { newRoot: <replacementDocument> } }

替换文档可以是任何解析为文档的有效表达式。如果 <replacementDocument> 不是文档,则该阶段会出错并失败。有关表达式的更多信息,请参阅表达式

If the <replacementDocument> is not a document, $replaceRoot errors and fails.

If the <replacementDocument> resolves to a missing document (i.e. the document does not exist), $replaceRoot errors and fails. For example, create a collection with the following documents:

db.collection.insertMany([
{ "_id": 1, "name" : { "first" : "John", "last" : "Backus" } },
{ "_id": 2, "name" : { "first" : "John", "last" : "McCarthy" } },
{ "_id": 3, "name": { "first" : "Grace", "last" : "Hopper" } },
{ "_id": 4, "firstname": "Ole-Johan", "lastname" : "Dahl" },
])

Then the following $replaceRoot operation fails because one of the documents does not have the name field:

db.collection.aggregate([
{ $replaceRoot: { newRoot: "$name" } }
])

为了避免该错误,您可以使用$mergeObjectsname文档合并到某个默认文档中;例如:

db.collection.aggregate([
{ $replaceRoot: { newRoot: { $mergeObjects: [ { _id: "$_id", first: "", last: "" }, "$name" ] } } }
])
[
{ _id: 1, first: 'John', last: 'Backus' },
{ _id: 2, first: 'John', last: 'McCarthy' },
{ _id: 3, first: 'Grace', last: 'Hopper' },
{ _id: 4, first: '', last: '' }
]

Alternatively, you can skip the documents that are missing the name field by including a $match stage to check for existence of the document field before passing documents to the $replaceRoot stage:

db.collection.aggregate([
{ $match: { name : { $exists: true, $not: { $type: "array" }, $type: "object" } } },
{ $replaceRoot: { newRoot: "$name" } }
])
[
{ first: 'John', last: 'Backus' },
{ first: 'John', last: 'McCarthy' },
{ first: 'Grace', last: 'Hopper' }
]

也可以使用 $ifNull 表达式指定其他文档作为根文档;例如:

db.collection.aggregate([
{ $replaceRoot: { newRoot: { $ifNull: [ "$name", { _id: "$_id", missingName: true} ] } } }
])
[
{ first: 'John', last: 'Backus' },
{ first: 'John', last: 'McCarthy' },
{ first: 'Grace', last: 'Hopper' },
{ _id: 4, missingName: true }
]

一个名为 people 的集合包含以下文档:

db.people.insertMany([
{ "_id" : 1, "name" : "Arlene", "age" : 34, "pets" : { "dogs" : 2, "cats" : 1 } },
{ "_id" : 2, "name" : "Sam", "age" : 41, "pets" : { "cats" : 1, "fish" : 3 } },
{ "_id" : 3, "name" : "Maria", "age" : 25 }
])

The following operation uses the $replaceRoot stage to replace each input document with the result of a $mergeObjects operation. The $mergeObjects expression merges the specified default document with the pets document.

db.people.aggregate( [
{ $replaceRoot: { newRoot: { $mergeObjects: [ { dogs: 0, cats: 0, birds: 0, fish: 0 }, "$pets" ] } } }
] )
[
{ dogs: 2, cats: 1, birds: 0, fish: 0 },
{ dogs: 0, cats: 1, birds: 0, fish: 3 },
{ dogs: 0, cats: 0, birds: 0, fish: 0 }
]

一个名为 students 的集合包含以下文档:

db.students.insertMany([
{
"_id" : 1,
"grades" : [
{ "test": 1, "grade" : 80, "mean" : 75, "std" : 6 },
{ "test": 2, "grade" : 85, "mean" : 90, "std" : 4 },
{ "test": 3, "grade" : 95, "mean" : 85, "std" : 6 }
]
},
{
"_id" : 2,
"grades" : [
{ "test": 1, "grade" : 90, "mean" : 75, "std" : 6 },
{ "test": 2, "grade" : 87, "mean" : 90, "std" : 3 },
{ "test": 3, "grade" : 91, "mean" : 85, "std" : 4 }
]
}
])

以下操作将 grade 字段大于或等于 90 的嵌入式文档提升到顶层:

db.students.aggregate( [
{ $unwind: "$grades" },
{ $match: { "grades.grade" : { $gte: 90 } } },
{ $replaceRoot: { newRoot: "$grades" } }
] )
[
{ test: 3, grade: 95, mean: 85, std: 6 },
{ test: 1, grade: 90, mean: 75, std: 6 },
{ test: 3, grade: 91, mean: 85, std: 4 }
]

您还可以在 $replaceRoot 阶段创建新文档,并用它们替换所有其他字段。

一个名为 contacts 的集合包含以下文档:

db.contacts.insertMany([
{ "_id" : 1, "first_name" : "Gary", "last_name" : "Sheffield", "city" : "New York" },
{ "_id" : 2, "first_name" : "Nancy", "last_name" : "Walker", "city" : "Anaheim" },
{ "_id" : 3, "first_name" : "Peter", "last_name" : "Sumner", "city" : "Toledo" }
])

以下操作根据 first_namelast_name 字段创建新文档。

db.contacts.aggregate( [
{
$replaceRoot: {
newRoot: {
full_name: {
$concat : [ "$first_name", " ", "$last_name" ]
}
}
}
}
] )
[
{ full_name: 'Gary Sheffield' },
{ full_name: 'Nancy Walker' },
{ full_name: 'Peter Sumner' }
]

一个名为 contacts 的集合包含以下文档:

db.contacts.insertMany( [
{ "_id" : 1, name: "Fred", email: "fred@example.net" },
{ "_id" : 2, name: "Frank N. Stine", cell: "012-345-9999" },
{ "_id" : 3, name: "Gren Dell", home: "987-654-3210", email: "beo@example.net" }
] )

The following operation uses $replaceRoot with $mergeObjects to output current documents with default values for missing fields:

db.contacts.aggregate( [
{ $replaceRoot:
{ newRoot:
{ $mergeObjects:
[
{ _id: "", name: "", email: "", cell: "", home: "" },
"$$ROOT"
]
}
}
}
] )
[
{ _id: 1, name: 'Fred', email: 'fred@example.net', cell: '', home: '' },
{
_id: 2,
name: 'Frank N. Stine',
email: '',
cell: '012-345-9999',
home: ''
},
{
_id: 3,
name: 'Gren Dell',
email: 'beo@example.net',
cell: '',
home: '987-654-3210'
}
]

本页上的C#示例使用Atlas示例数据集中的 sample_mflix数据库。要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅MongoDB .NET/ C#驱动程序文档中的入门

以下 Movie 类对 sample_mflix.movies 集合中的文档进行建模:

[BsonIgnoreExtraElements]
public class Movie
{
[BsonId]
public ObjectId Id { get; set; }
[BsonElement("title")]
public string Title { get; set; } = null!;
[BsonElement("year")]
public int? Year { get; set; }
[BsonElement("runtime")]
public int? Runtime { get; set; }
[BsonElement("rated")]
public string? Rated { get; set; }
[BsonElement("metacritic")]
public int Metacritic { get; set; }
[BsonElement("plot")]
public string? Plot { get; set; }
[BsonElement("type")]
public string? Type { get; set; }
[BsonElement("cast")]
public string[]? Cast { get; set; }
[BsonElement("directors")]
public string[]? Directors { get; set; }
[BsonElement("writers")]
public string[]? Writers { get; set; }
[BsonElement("imdb")]
public ImdbData? Imdb { get; set; }
}

以下 ImdbData 类对嵌入的 imdb 文档进行建模:

[BsonIgnoreExtraElements]
public class ImdbData
{
[BsonElement("id")]
public int? ImdbId { get; set; }
[BsonElement("rating")]
public double? Rating { get; set; }
[BsonElement("votes")]
public int? Votes { get; set; }
}

To use the MongoDB .NET/C# driver to add a $replaceRoot stage to an aggregation pipeline, call the UnionWith() method on a PipelineDefinition object.

以下示例创建一个管道阶段,用于过滤器具有 imdb 字段的 Movie 文档,按标题对其进行排序,将结果限制为五个文档,并将每个文档替换为其嵌入的 ImdbData 文档:

var pipeline = new EmptyPipelineDefinition<Movie>()
.Match(Builders<Movie>.Filter.Exists(m => m.Imdb))
.Sort(Builders<Movie>.Sort.Ascending(m => m.Title))
.Limit(5)
.ReplaceRoot(m => m.Imdb);

本页上的 Node.js 示例使用 Atlas 示例数据集中的 sample_mflix数据库。要学习如何创建免费的MongoDB Atlas 集群并加载示例数据集,请参阅MongoDB Node.js驱动程序文档中的入门

要使用MongoDB Node.js驱动程序将 $replaceRoot 阶段添加到聚合管道,请在管道对象中使用 $replaceRoot操作符。

以下示例创建一个管道阶段,该阶段将每个输入 movie 文档替换为存储在其 imdb 属性中的文档。然后,示例运行聚合管道:

const pipeline = [{ $replaceRoot: { newRoot: "$imdb" } }];
const cursor = collection.aggregate(pipeline);
return cursor;

To learn more about related pipeline stages, see the $replaceRoot guide.

给本页内容打分