laravel-mongodb icon indicating copy to clipboard operation
laravel-mongodb copied to clipboard

Bulk/Batch upserts

Open ndarproj opened this issue 4 years ago • 3 comments

Is your feature request related to a problem?

RuntimeException with message 'This database engine does not support upserts.

Describe the solution you'd like

batch upsert https://laravel.com/docs/8.x/eloquent#upserts

Describe alternatives you've considered

foreach updateorcreate is very slow

ndarproj avatar May 28 '21 13:05 ndarproj

@ndarproj did you manage to have a work around ?

ianrussel avatar Mar 01 '22 08:03 ianrussel

for the moment I was able to get it working like this

PostModel::raw(function ($collection) use($data) {
            $bulkResp = collect($data)
                ->reduce(function($acc, $itm) {
                    $acc[] = [
                        'updateOne' => [
                                ['transaction_id' => $itm['key1']], // update condition
                                ['$set' => $itm, '$setOnInsert' => ['key2' => null]], // set the update object data
                                ['upsert' => true]
                            ]
                    ];
                    return $acc;
                }, []);

            if (!empty($bulkResp))
                $collection->bulkWrite($bulkResp);
            return;
        });

ref: https://github.com/jenssegers/laravel-mongodb#:~:text=You%20can%20also%20perform%20raw%20expressions%20on%20the%20internal%20MongoCollection%20object.%20If%20this%20is%20executed%20on%20the%20model%20class,%20it%20will%20return%20a%20collection%20of%20models.

https://i.imgur.com/XdLcyyN.png

https://www.mongodb.com/docs/php-library/current/reference/method/MongoDBCollection-bulkWrite/

DishantPal avatar Sep 21 '22 12:09 DishantPal

Tracker in PHPORM-114

GromNaN avatar Nov 10 '23 10:11 GromNaN