PHP7裡面使用如下庫,操作比較複雜 PHP7連接MongoDB語法如下: //參數規則: mongodb://賬號:密碼@IP:埠/資料庫 $manager = new \MongoDB\Driver\Manager("mongodb://php:123456@localhost:27017/p ...
目錄
PHP7裡面使用如下庫,操作比較複雜
PHP7連接MongoDB語法如下:
//參數規則: mongodb://賬號:密碼@IP:埠/資料庫
$manager = new \MongoDB\Driver\Manager("mongodb://php:123456@localhost:27017/php");
插入數據
//1.連接MongoDB
$manager = new \MongoDB\Driver\Manager("mongodb://php:123456@localhost:27017/php");
//2.創建一個BulkWrite對象
$bulk = new \MongoDB\Driver\BulkWrite();
$bulk->insert(['name' => 'bashlog', 'age' => 26, 'email' => '[email protected]']);
$bulk->insert(['name' => 'itbsl', 'age' => 12, 'email' => '[email protected]']);
//3.執行插入
$manager->executeBulkWrite('php.stu', $bulk);
查看插入情況
查詢數據
//1.連接MongoDB
$manager = new \MongoDB\Driver\Manager("mongodb://php:123456@localhost:27017/php");
//2.創建一個Query對象
$filter = ['age' => ['$gt' => 5]];
$options = [
'sort' => ['age' => -1]
];
$query = new \MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery('php.stu', $query);
foreach ($cursor as $document) {
var_dump($document);
}
更新數據
//1.規則:mongodb://賬號:密碼@IP:埠/資料庫
$manager = new \MongoDB\Driver\Manager("mongodb://php:123456@localhost:27017/php");
//2.創建一個BulkWrite對象
$bulk = new \MongoDB\Driver\BulkWrite();
$bulk->update(
['age' => 12],
['$set' => ['name' => 'kitty', 'age' => 122]],
['multi' => false, 'upsert' => false]
);
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('php.stu', $bulk, $writeConcern);
刪除數據
//1.規則:mongodb://賬號:密碼@IP:埠/資料庫
$manager = new \MongoDB\Driver\Manager("mongodb://php:123456@localhost:27017/php");
//2.創建一個BulkWrite對象
$bulk = new \MongoDB\Driver\BulkWrite();
//limit為1時,刪除第一條匹配的數據
//limit為0時,刪除所有匹配數據
$bulk->delete(['age' => 122], ['limit' => 1]);
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('php.stu', $bulk, $writeConcern);