PHP7操作MongoDB


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' => 'bashlog@foxmail.com']);
$bulk->insert(['name' => 'itbsl', 'age' => 12, 'email' => 'itbsl@foxmail.com']);

//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);

如果該文章對您有幫助,請您點個推薦,感謝。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM