【问题标题】:Delete one element from an array in MongoDB? [duplicate]从 MongoDB 的数组中删除一个元素? [复制]
【发布时间】:2018-11-08 08:25:39
【问题描述】:

我将以下文档存储在 mongo DB 集合中,我将动态接收要删除的 url 例如,我需要删除名称“name”的订阅者 url http://localhost.8080/FNOL/subscriber1:“FNOL”,“国家” " : "US","lob" : 文档中的 "property"。

如何用 mongo 编写删除命令?

我需要重新定义我的文档结构吗?

提前致谢。

{
        "_id" : ObjectId("5b07fbbc0d7a677d2f8b2d87"),
        "name" : "FNOL",
        "country" : "US",
        "lob" : "property",
        "subscribers" : [
                {
                        "protocol" : "REST",
                        "url" : "http://localhost.8080/FNOL/subscriber1"
                },
                {
                        "protocol" : "SOAP",
                        "url" : "http://localhost.8080/FNOL/subscriber2"
                },
                {
                        "protocol" : "JMS",
                        "url" : "NOTIFICATION.TOPIC.FNOL"
                }
        ]
}

移除后:

{
            "_id" : ObjectId("5b07fbbc0d7a677d2f8b2d87"),
            "name" : "FNOL",
            "country" : "US",
            "lob" : "property",
            "subscribers" : [

                    {
                            "protocol" : "SOAP",
                            "url" : "http://localhost.8080/FNOL/subscriber2"
                    },
                    {
                            "protocol" : "JMS",
                            "url" : "NOTIFICATION.TOPIC.FNOL"
                    }
            ]
    }

【问题讨论】:

  • 使用 mongo shell?

标签: mongodb


【解决方案1】:

您可以使用$pull 运算符指定提到的条件来获取匹配的文档和url 作为$pull 的参数,如下所示:

let urlToRemove = "http://localhost.8080/FNOL/subscriber1";
db.col.update(
    { name: "FNOL", country: "US", lob: "property" }, 
    { $pull: { subscribers: {url: urlToRemove }}})

【讨论】:

  • 感谢它似乎可以与 mongo shell 一起使用。我将尝试使用骆驼 mongo 组件并在此问题上与您联系。
猜你喜欢
  • 2016-04-03
  • 2017-12-22
  • 2015-06-12
  • 2020-08-24
  • 2013-11-25
  • 2013-01-06
  • 1970-01-01
相关资源
最近更新 更多