加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

mongodb php

发布时间:2020-12-13 12:39:30 所属栏目:百科 来源:网络整理
导读:首先安装扩展,然后才能使用mongodb 一、连接数据库 try { $mongo = new MongoClient(); $db = $mongo - mydb; var_dump ( $db );} catch (MongoConnectionException $e ) { echo $e - getMessage();} 该代码可以连接mydb数据库,如果该数据库不存在则自动创

首先安装扩展,然后才能使用mongodb

一、连接数据库

try {
    $mongo = new MongoClient();
    $db = $mongo->mydb;
    var_dump($db);
} catch (MongoConnectionException $e) {
    echo $e->getMessage();
}

该代码可以连接mydb数据库,如果该数据库不存在则自动创建。

二、创建集合

mydb;
    $mycol = $db->createCollection('mycol');
    $mycolgetMessage();
}

该代码可以创建集合mycol。

三、插入文档

mongodb中使用insert()来插入文档。

$db->mycol;

    $document = array('name' => 'test1','sex' => 'formale','age' => 20);
    $res = $mycol->insert($document$resgetMessage();
}

输出:

array (size=4)
  'ok' => float 1
  'n' => int 0
  'err' => null
  'errmsg' => null

四、查找文档

mongodb使用find()来查找文档

$mongoCursor = $mycol->find();
    foreach ($mongoCursor as ) {
        );
    }
} getMessage();
}

结果:

)
  '_id' => 
    object(MongoId)[7]
      public '$id' => string '56c28a793b22cf5415000029' (length=24)
  'name' => string 'test1' (length=5)
  'sex' => string 'formale' (length=7)
  'age' => int 20

五、更新文档

使用update()来更新文档

$mycol->update(array('name'=>'test1'),array('$set'=>array('age' => 21)));
    getMessage();
}

结果

)
  'age' => int 21

六、删除文档

$mycol->remove(array('name'=>'test1'));
    getMessage();
}

remove方法

public bool|array MongoCollection::remove ([ array $criteria = array() [,1)">$options = array() ]] )

options删除的选项:

“w”:抛出异常的级别,默认是1;

“justOne”:最多只删除一个匹配的记录;

fsync”:Boolean,defaults to?FALSE. Forces the insert to be synced to disk before returning success. If?TRUE,an acknowledged insert is implied and will override setting?w?to?0.

timeout”:Integer,defaults to?MongoCursor::$timeout. If "safe" is set,this sets how long (in milliseconds) for the client to wait for a database response. If the database does not respond within the timeout period,aMongoCursorTimeoutException?will be thrown.

......

?

?

其他方法可参见php手册:http://php.net/manual/zh/book.mongo.php

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读