如何使用 $pull 在 mongodb 中删除数组内的文档 [英] How to remove a document inside an array in mongodb using $pull

查看:58
本文介绍了如何使用 $pull 在 mongodb 中删除数组内的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下文档结构

{
    "_id" : ObjectId("5ffef283f1f06ff8524aa2c2"),
    "applicationName" : "TestApp",
    "pName" : "",
    "environments" : [],
    "stages" : [],
    "createdAt" : ISODate("2021-01-15T09:51:35.546Z"),
    "workflows" : [ 
        [ 
            {
                "pName" : "Test1",
                "wName" : "TestApp_Test1",
                "agent" : ""
            }, 
            {
                "pName" : "Test2",
                "wName" : "TestApp_Test2",
                "agent" : ""
            }
        ], 
        [ 
            {
                "pName" : "Test1",
                "wName" : "TestApp_Test1",
                "agent" : ""
            }
        ]
    ],
    "updatedAt" : Date(-62135596800000)
}

我希望删除出现的

{
        "pName" : "Test1",
        "wName" : "TestApp_Test1",
        "agent" : ""
}

所以,生成的文档应该是这样的

So, the resultant document should look like

{
        "_id" : ObjectId("5ffef283f1f06ff8524aa2c2"),
        "applicationName" : "TestApp",
        "pName" : "",
        "environments" : [],
        "stages" : [],
        "createdAt" : ISODate("2021-01-15T09:51:35.546Z"),
        "workflows" : [ 
            [ 
                {
                    "pName" : "Test2",
                    "wName" : "TestApp_Test2",
                    "agent" : ""
                }
            ]
        ],
        "updatedAt" : Date(-62135596800000)
    }

我已经尝试过下面的 mongo 查询

I've tried the below mongo query

db.getCollection('workflows').update({_id:ObjectId('5ffef283f1f06ff8524aa2c2')}, {$pull:{workflows: { $elemMatch: {pipelineName: 'Test1'}}}} )

这是从工作流字段中删除所有文档,包括 Test2,因为 Test1 匹配.

This is removing all the documents from workflows field including Test2 since Test1 is matched.

我们如何只删除 Test1 的条目并保留其他条目?

How can we remove only the entries for Test1 and keep the others ?

推荐答案

您可以使用位置运算符$[]"来完成此操作;:

You can do it using the positional operator "$[]" :

db.getCollection('workflows').update({_id: ObjectId("5ffef283f1f06ff8524aa2c2")  }, {$pull: {"workflows.$[]":{pName:"Test1"  } }  } )

但架构看起来有点奇怪,更新后,如果子数组中的所有元素都被删除,工作流中将出现空数组.要修复空子数组,您需要执行第二个操作来删除它们:

but the schema looks abit strange and after the update you will have empty arrays inside workflows if all elements got deleted in the sub-array. To fix the empty sub-arrays you will need to perform second operation to remove them:

db.getCollection('workflows').update({_id: ObjectId("5ffef283f1f06ff8524aa2c2")  }, {$pull: {"workflows":[]  } }   )

这篇关于如何使用 $pull 在 mongodb 中删除数组内的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆