mongodb / laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)
https://www.mongodb.com/docs/drivers/php/laravel-mongodb/
MIT License
7k stars 1.43k forks source link

bulkWrite() yielding the error message: Missing first argument for $operations[0][\"updateOne\"] #2316

Open tomosterlund opened 3 years ago

tomosterlund commented 3 years ago

Description:

In a Laravel project that I'm working on, we now have a use case where we would like to access the MongoDB bulkWrite() operation, in order to iterate over objects that users have updated, and create multiple updateOne-Operations to send off to MongoDB, all in one request - see https://docs.mongodb.com/manual/core/bulk-write-operations/

The query is built as following:

$bulkWriteQuery = [];

foreach ($listOfUpdatedModels as $key => $userUpdatedModel) {
    $singleOperationQuery = [
        'updateOne' => [
            'filter' => ['_id' => $key],
            'update' => [
                '$set' => $userUpdatedModel
            ]
        ]
    ];

    $bulkWriteQuery[] = $singleOperationQuery;
}

And we then try to send it off to the DB like:

return $this->model()::raw(function($collection) use ($bulkWriteQuery) {
    return $collection->bulkWrite($bulkWriteQuery);
});

Error message

On this we receive the following error message: Missing first argument for $operations[0][\"updateOne\"]

Is bulkWrite() not supported, or am I missing out on something obvious here?

david-m-sitation commented 3 years ago

Just ran into this earlier as well.

Your array structure doesn't need the "filter" or "update" keys, try just sending the variables themselves.

$singleOperationQuery = [
        'updateOne' => [
            ['_id' => $key],
            ['$set' => $userUpdatedModel]
        ]
    ];

Also, if you're gonna do a "replaceOne" instead, you just send the document you're replacing w/out "replacement" or "$set" keys.