| 新写法 | { $replaceWith: <表达式> } |
|---|---|
| 旧写法 | { $replaceRoot: { newRoot: <表达式> } } |
| 典型组合 | $unwind 或 $arrayElemAt 取出的子文档作为新根 |
示例
示例
db.orders.aggregate([
{ $unwind: "$items" },
{ $replaceWith: "$items" },
{ $sort: { qty: -1 } }
])重塑后字段路径随之改变,下游阶段按新结构书写。
$replaceWith 用指定对象替换输出文档结构(旧名 $replaceRoot + newRoot),配合 $arrayElemAt 可把数组元素提升为文档。
| 新写法 | { $replaceWith: <表达式> } |
|---|---|
| 旧写法 | { $replaceRoot: { newRoot: <表达式> } } |
| 典型组合 | $unwind 或 $arrayElemAt 取出的子文档作为新根 |
db.orders.aggregate([
{ $unwind: "$items" },
{ $replaceWith: "$items" },
{ $sort: { qty: -1 } }
])