0

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 ?

2 Answers 2

1

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
 }
)
Sign up to request clarification or add additional context in comments.

2 Comments

I want to add new site embedded document in to the array. not just newsite
I have updated my answer as per your requirement. Kindly try that out.
1

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

1 Comment

I want to add embedded document in to the array. not just newsite

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.