首页 > 解决方案 > Mongo DB 更新查询

问题描述

我将以下文档存储在 mongo DB 集合中,我需要添加新订阅者 例如,我需要添加带有“协议”的订阅者:“SOAP”和 url http ://localhost.8080/FNOL/subscriber3文件中的名称 "name" : "FNOL","country" : "US","lob" : "property"。

如果我们添加的 url 已经存在,我们不应该添加到文档中,以防文档不存在匹配条件名称 "name" : "FNOL","country" : "US","lob" : "属性”我需要插入一个新文档。

是否可以在 mongo db 中的单个命令中完成上述所有操作?

提前致谢。

 {
            "_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"
                    },
                    {
                            "protocol" : "SOAP",
                            "url" : "http://localhost.8080/FNOL/subscriber2"
                    }
        ,
                    {
                            "protocol" : "SOAP",
                            "url" : "http://localhost.8080/FNOL/subscriber3"
                    }   
            ]
    }

标签: mongodb

解决方案


You need to use $addToSet... It will not push the data if it already exist in the array

db.collection.update(
  { name: 'FNOL', country: 'US', lob: 'property' },
  { $addToSet: { subscribers: { "protocol" : "SOAP", url: 'http://localhost.8080/FNOL/subscriber3' } } },
  { upsert: true }
)

推荐阅读