MongoDB聚合:$replaceWith

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

replaceWith‘可以将输入文档替换为指定的文档。该操作可以替换输入文档的所有字段,包括‘id‘字段。使用‘replaceWith`可以将输入文档替换为指定的文档。该操作可以替换输入文档的所有字段,包括`_id`字段。使用`replaceWith可以将输入文档替换为指定的文档。该操作可以替换输入文档的所有字段,包括id字段。使用replaceWith还可以将内嵌文档提升到最顶级,也可以把它替换掉。替换文档可以是任何能够解析为文档的有效表达式。replaceWith‘与‘replaceWith`与`replaceWithreplaceRoot`有很多相似点,但也有一些不同点。

语法

{
   
    $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" }
])

要避免上面的错误,可以使用$mergeObjectsname文档与某个缺省文档合并,如:

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" : 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

原子星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值