• 使用PHP来开发MongoDB并在shell查看数据


    1、shell连接使用mongoDB:

    启动mongodb: mongod --dbpath d:mongoDBdb

    打开新shell,连接mongodb:mongo


    2、shell基本命令:

    MongoDB命令行操作

    查看所有数据库:show dbs

    使用某个数据库:use mydb

    查看所有集合:show collections

    查看某个集合的所有元素:db.mycollection.find()

    指定某个值来查看相应的元素:db.mycollection.find({name : "wing jay"},{name:1 ,age:1 ,id:0})

    删除数据库: db.dropDatabase() 

    查看当前数据库: db  

    查看当前所有collection: show collections  

    新建集合collection: db.createCollection("student"){"name" : "xiaoming"} 或者 db.student.insert({"name" : "xiaoming"})

    删除集合collection:db.student.drop()

    重命名集合collection:db.student.renameCollection("STUDENT"){"name" : "xiaoming"}


    3、使用php代码来执行mongoDB数据库操作

    首先要在php中配置好mongoDB,同时安装好mongoDB数据库。

    1、连接数据库

    mongodb默认的初始用户名和密码均为admin。

    建立文件mongotest.php,设置连接所需用户名和密码,建立数据库连接

    <?php  
    //设置utf-8编码格式
    header("Content-type: text/html; charset=utf-8"); 
    $conn = new Mongo("mongodb://localhost:27017//admin:admin"); //默认用户和密码为admin //选择数据库blog,如果没有,则创建 $db = $conn->blog; //也可以写成:$db = $conn->selectDB('blog'); //制定结果集(表名:posts) $collection = $db->posts; //也可以写成:$collection = $db->selectCollection('posts'); ?>

    这样就成功创建了blog数据库和新的数据集posts(相当于SQL中的数据表概念)

    2、新增数据(Create)

    //新增一条blog posts  
    $post = array('title' => '第一篇博客', 'content' => '这是第一篇博客的内容.');  
    $collection->insert($post);  

    新增成功后,数据内容为:

    array(3) { ["_id"]=> object(MongoId)#8 (1) { ["$id"]=> string(24) "4ee0799de1fecdbc16000001" } ["title"]=> string(15) "第一篇博客" ["content"]=> string(31) "这是第一篇博客的内容." }  

    3、查询数据(Read)

    //查找  
    $cursor = $collection->find();  
    foreach($cursor as $key => $value){  
        var_dump($value);  
    }  

    4、更新数据(Update)

    $newdata = array('$set' => array("content"=>"这是更新过的第一篇博客的内容."));  
    $collection->update(array("title" => "第一篇博客"), $newdata);  

    更新成功后的数据内容为:

    array(3) { ["_id"]=> object(MongoId)#7 (1) { ["$id"]=> string(24) "4ee0799de1fecdbc16000001" } ["content"]=> string(43) "这是更新过的第一篇博客的内容." ["title"]=> string(15) "第一篇博客" }  

    批量更新

    $content_1 = array('title' => '第一篇博客', 'content' => '今天好开心');
    $newdata = array('$set' =>array('content' => '今天不仅开心还运气特别好哈哈哈' ));
    $filter = array('title' => '第一篇博客'); //过滤器
    $options['multiple'] = true; //批量更新
    $collection->update($filter,$newdata,$options);

    5、删除数据(Delete)

     
    //删除  
    $collection->remove(array('title'=>'第一篇博客'));  

    6、其它常用操作

    //关闭连接  
    $conn->close();  
      
    //删除一个数据库  
    $conn->dropDB("blog");  
      
    //列出所有可用数据库  
    $dbs = $conn->listDBs();  
  • 相关阅读:
    Directx11教程(6) 画一个简单的三角形(2)
    Zorder curve
    SmartGit 3.0.10 发布,图形化 Git 客户端
    PostgreSQL 全系版本更新,强烈要求升级!
    高保真PDF至HTML转换 pdf2htmlEX
    使用 pygit2 创建提交
    NetBSD 6.0 RC2 发布
    pyinstall 安装及配置
    Python for .NET
    Kundera 2.1 发布,NoSQL 的 ORM 框架
  • 原文地址:https://www.cnblogs.com/wingjay/p/3948196.html
Copyright © 2020-2023  润新知