简体   繁体   English

使用Java更新数组中的嵌入式文档,而无需在MongoDb中重复

[英]Update Embedded Documents in array without Repeating in MongoDb using Java

I have the following structure in my document: 我的文档中具有以下结构:

{
  "_id": 11111,
  "user": "user@mail.com",
  "sites": [
    {
      "sitename": "site1",
      "url": "site2.com",
      "keywords": [],
    },
    {
      "sitename": "site2",
      "url": "site2.com",
      "keywords": [],
    },
    {
      "sitename": "site2",
      "url": "site2.com",
      "keywords": [],
    },
  ]
},{
  "_id": 2222,
  "user": "user2@mail.com",
  "sites": []
}

I'm going to find the document by ID(id:11111).there is multiple documents. 我将通过ID(id:11111)查找该文档。有多个文档。 Then I want to add new site to sites array in the document that contain 1111 _id. 然后,我想向包含1111 _id的文档中的站点数组添加新站点。 if sitename already have, the site should not add. 如果站点名称已经存在,则不应添加该站点。 How can I achieve this ? 我该如何实现?

something like 就像是

db.collection.update({_id:11111, 'sites.sitename' : {$exists:false}},
 {$set : {'sites.$.sitename':'newsite.com'}},{multi:true})

Edit 编辑

if you want to add a sub-document for sitename 如果要添加站点名称的子文档

var sub = {'a':'a','b':'b'};

db.collection.update({_id:11111, 'sites.sitename' : {$exists:false}},
     {$set : {'sites.$.sitename':sub}},{multi:true})

Updated Answer : 更新的答案:

You can check that the _id is '11111', then check that the sitename doesn't exist and is not equal to the new sitename. 您可以检查_id为'11111',然后检查该sitename不存在并且不等于新的站点名称。 And then you can $push the embedded document into the array. 然后,您可以$push嵌入式文档$push到数组中。

db.collection.update(
 {
    _id:11111,
    'sites.sitename' : {$exists:false},
    'sites.sitename' : {$ne:'site4'}
 },
 {
    $push:
    {
        'sites': 
        {
            "sitename": "site4",
            "url": "site4.com",
            "keywords": []
        }
    }
 },
 {
    multi:true
 }
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM