• php操作mongodb:添删改查


    1:插入数据

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

    $manager = new MongoDBDriverManager("mongodb://localhost:27017");  
    
    // 插入数据
    $bulk = new MongoDBDriverBulkWrite;
    $bulk->insert(['id' => 1, 'name'=>'测试', 'url' => 'http://www.百度.com']);
    $manager->executeBulkWrite('test.wj', $bulk);

    2:查询数据

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

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

    3:更新数据

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

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

    广州VI设计公司https://www.houdianzi.com

    4:删除数据

    $bulk = new MongoDBDriverBulkWrite;
    $bulk->delete(['id' => 1], ['limit' => 1]);   // limit 为 1 时,删除第一条匹配数据
    $bulk->delete(['id' => 2], ['limit' => 0]);   // limit 为 0 时,删除所有匹配数据
    $manager = new MongoDBDriverManager("mongodb://localhost:27017");  
    $writeConcern = new MongoDBDriverWriteConcern(MongoDBDriverWriteConcern::MAJORITY, 1000);
    $result = $manager->executeBulkWrite('test.wj', $bulk, $writeConcern);
  • 相关阅读:
    一文搞懂Raft算法
    设计数据密集型应用第三部分:派生数据
    对一次架构设计的总结和反思
    One take,可望而不可即
    设计数据密集型应用第二部分:分布式系统的机遇与挑战
    [代码重构]简化函数调用
    [代码重构]简化函数调用
    [Vue专题] 对比vue-cli2.x和vue-cli3.x的搭建
    npm ERR! code ENOLOCAL
    Jenkins配置基于角色的项目权限管理
  • 原文地址:https://www.cnblogs.com/qianxiaox/p/14047728.html
Copyright © 2020-2023  润新知