Mongo DB更新查询

时间:2018-05-29 16:28:38

标签: mongodb

我将以下文档存储在mongo数据库集合中,我需要添加新订阅者例如,我需要添加订阅者" protocol" :" SOAP"和网址http://localhost.8080/FNOL/subscriber3的名称"名称" :" FNOL"," country" :" US"," lob" :"财产"来自该文件。

如果我们添加的网址已经存在,我们就不应该添加到文档中,以防文档中不存在匹配条件名称" 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"
                    }   
            ]
    }

2 个答案:

答案 0 :(得分:1)

你需要使用$addToSet ...如果数据已存在于数组中,它将不会推送数据

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

答案 1 :(得分:0)

试试这个。

db.collection.update({&#34; _id&#34;:(对象的id)},{&#34; $ push&#34;:{&#34;订阅者&#34; :{&#34; url&#34;:&#34;(输入网址)&#34;,&#34;协议&#34;:&#34;(输入协议)&#34;}}})< /强>