php简单操作mongodb

52次阅读

共计 1367 个字符,预计需要花费 4 分钟才能阅读完成。

一:插入数据

例:向默认的 test 数据库的 wj 表中插入数据

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");  

// 插入数据
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['id' => 1, 'name'=>'测试', 'url' => 'http://www. 百度.com']);
$manager->executeBulkWrite('test.wj', $bulk);

2:查询数据

查询 test 数据库的 wj 表中 name 值不为测试的数据

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");  
$filter = ['name' => '测试'];
$options = ['projection' => ['_id' => 0],
    'sort' => ['name' => -1],
];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery('test.wj', $query);
foreach ($cursor as $document) {print_r($document);
}

3: 更新数据

将 test 数据库中的 wj 表中 id 为 1 的数据中 name 字段变为测试 1234,

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->update(['id' => 1],
    ['$set' => ['name' => '测试 1234']],
    ['multi' => false, 'upsert' => false]  #multi 表示只更新一条数据,upsert 表示如果不存在 update 的记录,不进行插入操作
);
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");  
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('test.wj', $bulk, $writeConcern);

4:删除数据

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->delete(['id' => 1], ['limit' => 1]);   // limit 为 1 时,删除第一条匹配数据
$bulk->delete(['id' => 2], ['limit' => 0]);   // limit 为 0 时,删除所有匹配数据
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");  
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('test.wj', $bulk, $writeConcern);

正文完
 0