replaceWith‘可以将输入文档替换为指定的文档。该操作可以替换输入文档的所有字段,包括‘id‘字段。使用‘replaceWith`可以将输入文档替换为指定的文档。该操作可以替换输入文档的所有字段,包括`_id`字段。使用`replaceWith‘可以将输入文档替换为指定的文档。该操作可以替换输入文档的所有字段,包括‘id‘字段。使用‘replaceWith还可以将内嵌文档提升到最顶级,也可以把它替换掉。替换文档可以是任何能够解析为文档的有效表达式。replaceWith‘与‘replaceWith`与`replaceWith‘与‘replaceRoot`有很多相似点,但也有一些不同点。
语法
{
$replaceWith: <replacementDocument> }
使用
如果<replacementDocument>不是一个文档或者被解析为一个错误的文档(如:文档不存在),都会失败,例如:使用下面的文档创建一个集合:
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" },
])
下面的$replaceWith会操作失败,因为最后一个文档缺少name字段:
db.collection.aggregate([
{
$replaceWith: "$name" }
])
要避免上面的错误,可以使用$mergeObjects把name文档与某个缺省文档合并,如:
db.collection.aggregate([
{
$replaceWith: {
$mergeObjects: [ {
_id: "$_id", first: "", last: "" }, "$name" ] } }
])
也可以使用$match阶段,在$replaceWith之前筛选掉name字段异常的数据:
db.collection.aggregate([
{
$match: {
name : {
$exists: true, $not: {
$type: "array" }, $type: "object" } } },
{
$replaceWith: "$name" }
])
亦或者使用$ifNull表达式来指定其它的文档,如:
db.collection.aggregate([
{
$replaceWith: {
$ifNull: [ "$name", {
_id: "$_id", missingName: true} ] } }
])
举例:
替换内嵌文档字段
使用下面的语句创建一个people集合:
db.people.insertMany([
{
"_id" : 1, "name" : "Arlene", "age" : 34, "pets" : {
"dogs" :

本文详细解释了MongoDB中的$replaceWith操作,包括如何替换文档结构、内嵌文档、数组中的文档以及使用默认值填充缺失字段。通过实例展示了如何在聚合管道中使用这个功能进行数据处理和格式转换。
最低0.47元/天 解锁文章
1277

被折叠的 条评论
为什么被折叠?



