Amal Madawa
Amal Madawa

Reputation: 197

Update Embedded Documents in array without Repeating in MongoDb using Java

I have the following structure in my document:

{
  "_id": 11111,
  "user": "[email protected]",
  "sites": [
    {
      "sitename": "site1",
      "url": "site2.com",
      "keywords": [],
    },
    {
      "sitename": "site2",
      "url": "site2.com",
      "keywords": [],
    },
    {
      "sitename": "site2",
      "url": "site2.com",
      "keywords": [],
    },
  ]
},{
  "_id": 2222,
  "user": "[email protected]",
  "sites": []
}

I'm going to find the document by ID(id:11111).there is multiple documents. Then I want to add new site to sites array in the document that contain 1111 _id. if sitename already have, the site should not add. How can I achieve this ?

Upvotes: 0

Views: 136

Answers (2)

Rahul Kumar
Rahul Kumar

Reputation: 2831

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})

Upvotes: 1

Subhashree Pradhan
Subhashree Pradhan

Reputation: 812

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. And then you can $push the embedded document into the array.

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

Upvotes: 1

Related Questions