首页 文章

Mongo DB更新查询[重复]

提问于
浏览
1

这个问题在这里已有答案:

我将以下文档存储在mongo DB集合中,我将需要添加新订阅者例如 . 我需要添加订阅者"protocol":"SOAP"和url http://localhost.8080/FNOL/subscriber3名称为"name":"FNOL","country":"US","lob":"property"来自该文件 .

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

  • 1

    您需要使用$addToSet ...如果数据已经存在,它将不会推送数据

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

    试试这个 .

    db.collection.update( { "_id": (id of the object) }, { "$push": {"subscribers": { "url": "(input url )", "protocol": "(input protocol)" } } } )

相关问题