0

I have a document in which one of the fields is an array of objects containing multiple fields.

{
    "_id" : "1",
    "data" : [ 
        {
            "time" : 500,
            "offset" : -20,
            "sample" : 10
        },
        {
            "time" : 700,
            "offset" : -20,
            "sample" : 30
        }
    ]
}

I want to be able to update the array with new entries and also overwrite update the value of sample if an entry with a specific "time" and "offset" already exist.

For example if I pass in an array with values

[ 
   {
       "time" : 500,
       "offset" : -20,
       "sample" : 20
   },
   {
       "time" : 600,
       "offset" : -20,
       "sample" : 10
   }
 ]

The expected output would be

{
    "_id" : "1",
    "data" : [ 
       {
           "time" : 500,
           "offset" : -20,
           "sample" : 20
       },
       {
           "time" : 600,
           "offset" : -20,
           "sample" : 10
       },
       {
           "time" : 700,
           "offset" : -20,
           "sample" : 30
       }
    ]
}

Is there a way to do this in a single statement?

5
  • You should insert the element into the Array if do not exists, but if fail - maybe exists - then update the element into the array. You can't do "insert/update" in one query. The first part is just an "updateOne" with some $and to check the elemento into the array. The second part is still updateOne with $elemMatch to seek the elemento into the Array. Commented Aug 29, 2018 at 15:30
  • Is it possible to do something like an update with a addToSet based on "time" and "offset" that way I would only insert the new elements on my first update statement? Commented Aug 29, 2018 at 16:34
  • 1
    This might be the answer for your question stackoverflow.com/questions/51801033/… Commented Aug 29, 2018 at 16:52
  • 1
    Brios: you can do something like "add this to the array if that do not exists in the array" or "modify that in the array if this exists". But you can't do it in one single statement "add this to the array if that do not exists in the array else modify that from the array with this" :-) Commented Aug 29, 2018 at 17:22
  • I was able to accomplish this by creating a bulkwrite to complete multiple statements in a single transaction. Commented Aug 30, 2018 at 13:35

0

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.