mongodb+php学习1
1 mongodb启动时,设置启动项
C:\>mongodb\bin\mongod --config C:\mongodb.conf
其中mongodb.conf为:
dbpath = D:\mongodb_data
logpath = D:\mongodb.log
logappend = true
如果是linux的话,则mongod --config /etc/mongodb.conf
2 停止server
db.shutdownServer()
3 常用操作:
use myfirstdb
插入db
db.movies.insert({name:"Source Code", genre:"sci-fi", year:2011})
查找所有记录
db.movies.find()
4 php 5.2 mongo driver下载:
http://downloads.mongodb.org/mongo-latestphp5.2vc6ts.
zip
5.3 mongo driver下载:
http://downloads.mongodb.org/mongo-latest-php5.3vc6ts.zip
把DLL复制到extension目录,然后
extension=php_mongo.dll即可
5 列出当前数据库的php mongodb程序
<?php
try{
$mongo = new Mongo(); //create a connection to MongoDB
$databases = $mongo->listDBs(); //List all databases
echo '<pre>';
print_r($databases);
$mongo->close();
} catch(MongoConnectionException $e) {
//handle connection error
die($e->getMessage());
}
?>
如果是连接时用不同的端口,构造函数中用:
$mongo = new Mongo($server="mongodb://localhost:8888");
也可以指定timeout的策略;
try {
$mongo = new Mongo($options=array('timeout'=> 100))
} catch(MongoConnectionException $e) {
die("Failed to connect to database ".$e->getMessage());
}
6 通过PHP保存对象到mongo db中
$connection = new Mongo();
$database = $connection->selectDB('myblogsite');
$collection = $database->selectCollection('articles');
$article = array();
$article['title'] = $_POST['title'];
$article['content'] = $_POST['content'];
$article['saved_at'] = new MongoDate();
$collection->insert($article);
注意的是,默认不用显式create database即可,如果不存在则会自动
新建立database,也可以:
$connection = new Mongo();
$collection = $connection->myblogsite->articles;
mongodb的插入是异步的,如果不想异步,可以这样;
try {
$status = $connection->insert(array('title' => 'Blog Title',
'content' => 'Blog Content'),
array('safe' => True));
echo "Insert operation complete";
} catch (MongoCursorException $e) {
die("Insert failed ".$e->getMessage());
}
则必须等插入完成后才返回给用户,继续执行下一条语句
也可以指定timeout的策略:
$collection->insert($document, array('safe' => True,
'timeout' => True));
7 设置自己的自增id
$document = array('_id' => hash('sha1', $username.time()),
将设置id为username后加上当前时间再hash.
8 日期设置
$article['saved_at'] = new MongoDate();
$timestamp = new MongoDate(strtotime('2011-05-21 12:00:00'));
print date('g:i a, F j', $timestamp->sec); //prints 12 pm, May 21
$lastweek = new MongoDate(strtotime('-1 w