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 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

can't I do it in single query?
No, you cannot for nested arrays. upsert works at document level
Thank you. I was trying to do in single query which may reduce one db hit in my application.

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.