On this page
$replaceRoot (aggregation)
在本页面
Definition
$replaceRoot
- 3.4 版的新功能。
将指定的文档提升到顶层,并替换所有其他字段。该操作将替换 Importing 文档中的所有现有字段,包括_id
字段。您可以将现有的嵌入式文档升级到顶层,也可以创建一个新的文档进行升级(请参见example)。
$replaceRoot阶段具有以下形式:
{ $replaceRoot: { newRoot: <replacementDocument> } }
替换文档可以是解析为文档的任何有效expression。
有关表达式的更多信息,请参见Expressions。
Behavior
如果<replacementDocument>
不是文档,则$replaceRoot
操作将失败并显示错误。
如果替换文档引用了 Importing 文档中不存在的字段,则该操作将失败并显示错误。为了确保存在替换文档,请先使用$match阶段检查是否存在,然后再将文档传递到$replaceRoot阶段(请参见example)。
Examples
$ replaceRoot 带有嵌入式文档
名为produce
的集合包含以下文档:
{
"_id" : 1,
"fruit" : [ "apples", "oranges" ],
"in_stock" : { "oranges" : 20, "apples" : 60 },
"on_order" : { "oranges" : 35, "apples" : 75 }
}
{
"_id" : 2,
"vegetables" : [ "beets", "yams" ],
"in_stock" : { "beets" : 130, "yams" : 200 },
"on_order" : { "beets" : 90, "yams" : 145 }
}
以下操作使用$replaceRoot阶段将in_stock
文档提升到顶层,并丢弃当前的顶层字段。
db.produce.aggregate( [
{
$replaceRoot: { newRoot: "$in_stock" }
}
] )
该操作返回以下文档:
{ "oranges" : 20, "apples" : 60 }
{ "beets" : 130, "yams" : 200 }
$ replaceRoot 具有$ match 阶段
名为people
的集合包含以下文档:
{ "_id" : 1, "name" : "Arlene", "age" : 34, "pets" : { "dogs" : 2, "cats" : 1 } }
{ "_id" : 2, "name" : "Sam", "age" : 41, "pets" : { "cats" : 1, "hamsters" : 3 } }
{ "_id" : 3, "name" : "Maria", "age" : 25 }
为了使用$replaceRoot
阶段运行聚合操作以将pets
字段提升到最高级别,您还需要包括$match
阶段以过滤出不包含pets
字段的所有文档。
db.people.aggregate( [
{
$match: { pets : { $exists: true } }
},
{
$replaceRoot: { newRoot: "$pets" }
}
] )
该操作返回以下结果:
{ "dogs" : 2, "cats" : 1 }
{ "cats" : 1, "hamsters" : 3 }
$ replaceRoot 和新创建的文档
您还可以在$replaceRoot
阶段中创建新文档,并使用它们替换所有其他字段。
名为contacts
的集合包含以下文档:
{ "_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_name
和last_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" }
$ replaceRoot 与数组元素
名为contacts
的集合包含以下文档:
{ "_id" : 1, "name" : "Susan",
"phones" : [ { "cell" : "555-653-6527" },
{ "home" : "555-965-2454" } ] }
{ "_id" : 2, "name" : "Mark",
"phones" : [ { "cell" : "555-445-8767" },
{ "home" : "555-322-2774" } ] }
以下操作将使用键cell
将嵌入的文档提升到顶层:
db.contacts.aggregate( [
{
$unwind: "$phones"
},
{
$match: { "phones.cell" : { $exists: true } }
},
{
$replaceRoot: { newRoot: "$phones"}
}
] )
该操作返回以下结果:
{ "cell" : "555-653-6527" }
{ "cell" : "555-445-8767" }