diff --git a/src/Client.php b/src/Client.php index 307f478..2f719eb 100644 --- a/src/Client.php +++ b/src/Client.php @@ -444,6 +444,34 @@ public function insert(string $collection, array $document, array $options = []) return $this->toArray($docObj); } + public function insertMany(string $collection, array $documents, array $options = []): array + { + $docObjs = []; + + foreach ($documents as $document) { + $docObj = new stdClass(); + + foreach ($document as $key => $value) { + if (\is_null($value)) { + continue; + } + + $docObj->{$key} = $value; + } + + $docObj->_id ??= new BSON\ObjectId(); + + $docObjs[] = $docObj; + } + + $this->query(array_merge([ + self::COMMAND_INSERT => $collection, + 'documents' => $docObjs, + ], $options)); + + return $this->toArray($docObjs); + } + /** * Retrieve the last lastDocument * diff --git a/tests/MongoTest.php b/tests/MongoTest.php index e2760a5..4040408 100644 --- a/tests/MongoTest.php +++ b/tests/MongoTest.php @@ -108,6 +108,34 @@ public function testCreateDocument() self::assertIsObject($doc->date_object); // Todo: This is not working can't retrieve the object back } + public function testCreateDocuments(): array + { + $docs = $this->getDatabase()->insertMany( + 'movies', + [ + [ + 'name' => 'Armageddon', + 'country' => 'USA', + 'language' => 'English' + ], + [ + 'name' => '9 Monkeys', + 'country' => 'USA', + 'language' => 'English' + ], + [ + 'name' => 300, + 'country' => 'USA', + 'language' => 'English' + ] + ] + ); + + self::assertCount(3, $docs); + + return $docs; + } + public function testUpdateDocument(): void { $this->getDatabase()->insert( @@ -133,26 +161,42 @@ public function testUpdateDocument(): void self::assertCount(1, $doc); } - public function testUpdateMultipleDocuments(): void + /** + * @depends testCreateDocuments + * @return void + * @throws Exception + */ + public function testUpdateDocuments(array $documents): void { $this->getDatabase()->update( 'movies', - ['name' => 'Armageddon 2'], - ['$set' => ['name' => 'Armageddon']] + updates: ['$set' => ['name' => 'Armageddon 2']], + multi: true ); + $docs = $this->getDatabase()->find( + 'movies', + filters: ['name' => 'Armageddon 2'] + )->cursor->firstBatch ?? []; + + self::assertCount(8, $docs); + } + + public function testUpdateMultipleDocuments(): void + { $this->getDatabase()->update( 'movies', - ['name' => 'Armageddon'], + ['name' => 'Armageddon 2'], ['$rename' => ['name' => 'title']], multi: true ); $docs = $this->getDatabase()->find( 'movies', - ['title' => 'Armageddon'] + ['title' => 'Armageddon 2'] )->cursor->firstBatch ?? []; - self::assertCount(2, $docs); + + self::assertCount(8, $docs); } public function testDriverException()