0

I have model like this

     {
     "array1": [
                {
                    "_id": "123",
                    "array2": [
                          {
                              "_id": "123",
                              "answeredBy": [],
                          }

                     ],
                 }
             ] 
}

If I have id in array1, push the document into array2 or create new document in array1.

Eg:

If I give have new object

{
   "_id": "456",
   "answeredBy": [],
} 

and if given _id of array1 as 123

the result should be

      {  
   "array1":[  
      {  
         "_id":"123",
         "array2":[  
            {  
               "_id":"123",
               "answeredBy":[  

               ],

            },
            {  
               "_id":"456",
               "answeredBy":[  

               ],

            }
         ],

      }

else if give _id of array1 as other than 123 i.e., non existing i.e., 657

the result sholud be

{  
   "array1":[  
      {  
         "_id":"123",
         "array2":[  
            {  
               "_id":"123",
               "answeredBy":[  

               ],

            },

         ],

      }      {  
         "_id":"657",
         "array2":[  
            {  
               "_id":"456",
               "answeredBy":[  

               ],

            }
         ],

      }

result should be

How can I achieve this?

1 Answers1

1

Your question is similar except you push in both updates.

It is not possible to perform your request atomically so you'll need two update queries one for each request.

Update when the matching outer record is found which results in a update by pushing the new element in the inner array.

db.col.update(
    {"array1._id": "123"},
    {"$push":{"array1.$.array2":{"_id":"456","answeredBy":[]}}}
)

Update when the outer record is not matched you will get modified count of 0.

db.col.update(
    {"array1._id": "657"},
    {"$push":{"array1.$.array2":{"_id":"456","answeredBy":[]}}}
)

if(nModified == 0) {
  db.col.update(
    {},
    {"$push":{"array1":{ "_id":"657","array2":[{"_id":"456","answeredBy":[]}}}}
  )
}

You can read the linked answer for more details.

s7vr
  • 73,656
  • 11
  • 106
  • 127