'Concat array fields while pushing into bucket

I have the following collection of buckets in my mongodb, documents look as follows:

{
    "bucketId": "1",
    "items": [
        {
            "alternativeIds": [
                "i-1"
            ],
            "uniqueId": "item-1"
        },
        {
            "alternativeIds": [
                "i-2"
            ],
            "uniqueId": "item-2"
        }
    ]
}

I need to insert the following object into the bucket:

{
    "bucketId": "1",
    "alternativeId": "it-1",
    "uniqueId": "item-1"
}

and the final result should look as follows:

{
    "bucketId": "1",
    "items": [
        {
            "alternativeIds": [
                "i-1",
                "it-1"
            ],
            "uniqueId": "item-1"
        },
        {
            "alternativeIds": [
                "i-2"
            ],
            "uniqueId": "item-2"
        }
    ]
}

Notice: if there is no "item-1" in the bucket, it must be inserted. Also, if there is no bucket "1" in the collection, it also must be created along with "item-1".

Is there a way to do this at once, with one single command, atomically?



Solution 1:[1]

Here's one way to do it.

db.collection.update({
  // find the required bucketId
  "bucketId": "1",
  // locate the items array element
  "items.uniqueId": "item-1"
},
{
  // push new value. Only works for finding
  // first "items.uniqueId": "item-1", but
  // should be OK if uniqueId is truly unique
  "$push": {
    "items.$.alternativeIds": "it-1"
  }
})

Try it on mongoplayground.net.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rickhg12hs