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

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

Open tomosterlund opened this issue 3 years ago • 1 comments

  • Laravel-mongodb Version: 7.0
  • PHP Version: 7.4
  • Database Driver & Version: 4.0

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?

tomosterlund avatar Sep 16 '21 13:09 tomosterlund

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.

david-m-sitation avatar Sep 17 '21 18:09 david-m-sitation