Skip to content

Instantly share code, notes, and snippets.

@laocoi
Last active June 20, 2018 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laocoi/418c7510611d06f46de68a4ba5dbf1b4 to your computer and use it in GitHub Desktop.
Save laocoi/418c7510611d06f46de68a4ba5dbf1b4 to your computer and use it in GitHub Desktop.

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


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment