Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ### Connect
- - - -
- ```
- use MongoDB\Client;
- $con = new Client("mongodb://127.0.0.1:27017", array("username" => "xxxx", "password" => "yyyy"));
- ```
- ### Find
- - - -
- ```
- $filter = ['field' => 'value'];
- $option = ['sort' => ['_id' => -1 ], 'limit' => 10];
- # -1 is desc, 1 is asc
- $data = $con->database->collection->find($filter,$option);
- foreach($data as $value){
- echo $value['_id'];
- }
- ```
- ### Insert
- - - -
- #### Insert many row
- ```
- #Connect Database
- $manager = new MongoDB\Driver\Manager("mongodb://127.0.0.1:27017", array("username" => "xxxx", "password" => "yyyyy"));
- $bulk = new MongoDB\Driver\BulkWrite(['ordered' => false]);
- #Preparing data
- $bulk->insert([
- 'field1' => 'value1',
- 'field2' => 'value2',
- 'field3' => 'value3'
- ]);
- $bulk->insert([
- 'field1' => 'value4',
- 'field2' => 'value5',
- 'field3' => 'value6'
- ]);
- #Insert data
- try {
- $result = $manager->executeBulkWrite('database.collection', $bulk);
- } catch (MongoDB\Driver\Exception\BulkWriteException $e) {
- var_dump($e->getWriteResult()->getWriteErrors());
- }
- ```
- Null, not null and compare
- ```
- #Where field not null
- 'field' => ['$exists' => true ]
- ```
- ### Update
- - - -
- ### UpdateOne
- - - -
- ```
- $updatedResult = $collection->updateOne(
- ['_id' => new MongoDB\BSON\ObjectId($id)],
- ['$set' => [
- 'field1' => 'value1',
- 'field2' => 'value2',
- ]
- );
- ```
- ### Delete
- - - -
Add Comment
Please, Sign In to add comment