php简单操作mongodb

热门标签

, , , , ,
admin

发表文章数:3048

一:插入数据

例:向默认的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);

未经允许不得转载:作者:admin, 转载或复制请以 超链接形式 并注明出处 夜河资源网
原文地址:《php简单操作mongodb》 发布于2019-12-26

分享到:
赞(0) 打赏

评论 抢沙发

1 + 2 =


撰写不易~如果您觉得文章对您有帮助的话可以打赏我哦~谢谢亲亲~

支付宝扫一扫打赏

微信扫一扫打赏

外服网游加速器破解版
包含腾讯网游加速器、海豚网游加速器等八款知名加速器,可加速外服游戏,永久包售后包更新,不定时添加新款破解版加速器!
切换注册

登录

忘记密码 ?

切换登录

注册