MongoDB 学习笔记

2010-12-15 10:55  3896人阅读  评论 (0)
Tags: mongo

MongoDB 命令行帮助

db.help()                    数据库帮助
db.mycoll.help()             集合帮助
rs.help()                    help on replica set methods
help connect                 链接服务器帮助
help admin                   管理命令
help misc                    杂项
show dbs                     show database names
show collections             show collections in current database
show users                   show users in current database
show profile                 show most recent system.profile entries wi
use <db_name>                选择数据库
db.foo.find()                查询集合
db.foo.find( { a : 1 } )     条件查询集合
it                           result of the last line evaluated; use to further iterate
exit                         quit the mongo shell

手册

链接数据库

$connection = new Mongo(); //默认端口27017
$connection = new Mongo("www.dotcoo.com");
$connection = new Mongo("www.dotcoo.com:12345");
$m = new Mongo("mongodb://${username}:${password}@localhost:12345/blog", array('persist'=>'p'));

验证用户名密码

$db->authenticate($username, $password);

获取数据库

$db = $connection->blog;

获取集合

$collection = $db->users;
$collection = $connection->blog->users;
$doc = array('username'=>'admin', 'password'=>'admin');

添加

$collection->insert($doc);

获取第一个

$obj = $collection->findOne();

获取集合的数量

echo $collection->count();

获得所有文档使用游标

$cursor = $collection->find(); //返回的是MongoCursor对象
foreach ($cursor as $id => $value) {
    echo "$id: ";
    var_dump( $value );
}

条件查询

$query = array( "i" => 71 );
$cursor = $collection->find( $query );
while( $cursor->hasNext() ) {
    var_dump( $cursor->getNext() );
}

条件查询

$query = array( "i" => array( '$gt' => 50 ) ); //$gt >, $lt <, $gte >=, $lte <=
$query = array( "i" => array( "\$gt" => 20, "\$lte" => 30 ) ); //多条件
$cursor = $coll->find( $query );
while( $cursor->hasNext() ) {
    var_dump( $cursor->getNext() );
}

设置查询的特殊字符

mongo.cmd = ":"

创建索引

$coll->ensureIndex( array( "i" => 1 ) );  // i 正序
$coll->ensureIndex( array( "i" => -1, "j" => 1 ) );  // i 正序, j 倒序

关闭连接

$connection->close();

负载均衡

$m = new Mongo("mongodb://localhost:27017", array("replicaSet" => true));
$result = $m->admin->command(array("ismaster" => 1));

持久连接

$m = new Mongo("localhost:27017", array("persist" => "x"));

域套接字

$m = new Mongo("mongodb://username:password@/tmp/mongo-27017.sock:0/foo");

安全操作

$collection->insert($someDoc);
$collection->update($criteria, $newObj);
$collection->insert($somethingElse);
$collection->remove($something, array("safe" => true));
$collection->insert($someDoc, array("safe" => 3));

查询 Query

根据id查询 MongoId

$person = array("name" => "joe");
$people->insert($person);
$joe = $people->findOne(array("_id" => $person['_id']));
$person = array("name" => "joe");
$people->insert($person);
// 转换 _id 为一个字符串
$pid = $person['_id'] . "";
// FAILS(失败) - $pid是一个字符串, 不是一个 MongoId 对象
$joe = $people->findOne(array("_id" => $pid));

索引的数组

$collection->save(array("awards" => array("gold", "silver", "bronze")));
// { "_id" : ObjectId("4b06c282edb87a281e09dad9"), "awards" : ["gold", "silver", "bronze"]}
$cursor = $collection->find(array("awards" => "gold"));

键值的数组或对象

{
    "_id" : ObjectId("4b06c282edb87a281e09dad9"),
    "awards" :
    [
        {"first place" : "gold"},
        {"second place" : "silver"},
        {"third place" :  "bronze"}
    ]
}
$cursor = $collection->find(array("awards.first place" => "gold"));
// 或
$cursor = $collection->find(array("awards" => array('$in' => array("gold", "copper"))));

更新 update

更新字段

$coll->update(array("username" => "joe"), array('$set' => array("twitter" => "@joe4153")));

更新文档

$coll->update(array("username" => "joe"), array("userId" => 12345, "info" => array(
    "name" => "joe", "twitter" => "@joe4153", "email" => "..."), "likes" => array()));

更新嵌套的对象

{
    "_id" : ObjectId("4b06c282edb87a281e09dad9"),
    "content" : "this is a blog post.",
    "comments" :
    [
        {
            "author" : "Mike",
            "comment" : "I think that blah blah blah...",
        },
        {
            "author" : "John",
            "comment" : "I disagree."
        }
    ]
}

更新制定下标

$blog->update($criteria, array('$set' => array("comments.1" => array("author" => "Jim"))));

更显所有的下标 $代表当前的下标

$blog->update(
    array("comments.author" => "John"),
    array('$set' => array('comments.$.author' => "Jim"))
);

安全 safe

防止注入 一般情况下不要拼接字符串

核心类

Mongo //数据库连接
MongoDB
MongoCollection
MongoCursor

http://www.php.net/manual/en/mongo.core.php

Mongo {
    /* Constants 常量 */
    const string Mongo::VERSION ; //驱动程序版本
    const string Mongo::DEFAULT_HOST = "localhost" ;
    const int Mongo::DEFAULT_PORT = 27017 ;
    /* Fields 字段 */
    public boolean $connected = FALSE ;
    public string $status = NULL ;
    protected string $server = NULL ;
    protected boolean $persistent = NULL ;
    /* Methods 方法 */
    public boolean close ( void ) //关闭数据库连接
    public boolean connect ( void ) //连接到数据库服务器
    protected boolean connectUtil ( void )
    __construct ([ string $server = "mongodb://localhost:27017" [, array $options = array("connect" => TRUE) ]] )
    public array dropDB ( mixed $db ) //已废弃
    public MongoDB __get ( string $dbname ) //获取数据库
    public array listDBs ( void ) //获取所有数据库列表
    public MongoCollection selectCollection ( string $db , string $collection ) //获取数据库集合
    public MongoDB selectDB ( string $name ) //获取数据库
    public string __toString ( void ) //本连接字符串表示形式
}

MongoDB {
    /* Constants */
    const int MongoDB::PROFILING_OFF = 0 ;
    const int MongoDB::PROFILING_SLOW = 1 ;
    const int MongoDB::PROFILING_ON = 2 ;
    /* Fields */
    public integer $w = 1 ;
    public integer $wtimeout = 10000 ;//
    /* Methods */
    public array authenticate ( string $username , string $password ) //登录
    public array command ( array $data ) //数据库命令
    __construct ( Mongo $conn , string $name )
    public MongoCollection createCollection ( string $name [, bool $capped = FALSE [, int $size = 0 [, int $max = 0 ]]] )
    public array createDBRef ( string $collection , mixed $a ) //创建一个外键
    public array drop ( void ) //删除此数据库
    public array dropCollection ( mixed $coll )
    public array execute ( mixed $code [, array $args = array() ] ) //执行数据库服务器上的JavaScript代码
    public bool forceError ( void )
    public MongoCollection __get ( string $name ) //获取集合
    public array getDBRef ( array $ref ) //获取一个外键
    public MongoGridFS getGridFS ([ string $prefix = "fs" ] )
    public int getProfilingLevel ( void )
    public array lastError ( void ) //最后一个错误
    public array listCollections ( void ) //获取集合列表
    public array prevError ( void ) //前一个错误
    public array repair ([ bool $preserve_cloned_files = FALSE [, bool $backup_original_files = FALSE ]] ) //修复数据库
    public array resetError ( void ) //清除所有错误
    public MongoCollection selectCollection ( string $name )
    public int setProfilingLevel ( int $level )
    public string __toString ( void )
}

MongoCollection {
    /* Constants */
    const int MongoCollection::ASCENDING = 1 ;
    const int MongoCollection::DESCENDING = -1 ;
    /* Fields */
    public MongoDB $db = NULL ;
    public integer $w ;
    public integer $wtimeout ;
    /* Methods */
    public mixed batchInsert ( array $a [, array $options = array() ] ) //批量插入
    public __construct ( MongoDB $db , string $name )
    public int count ([ array $query = array() [, int $limit = 0 [, int $skip = 0 ]]] ) //数量
    public array createDBRef ( array $a ) //创建外键
    public array deleteIndex ( string|array $keys ) //删除索引
    public array deleteIndexes ( void ) //删除所有索引
    public array drop ( void ) //删除集合
    public boolean ensureIndex ( array $keys , array $options ) //创建索引
    public MongoCursor find ([ array $query = array() [, array $fields = array() ]] ) //查找
    public array findOne ([ array $query = array() [, array $fields = array() ]] ) //查找第一个
    public MongoCollection __get ( string $name )
    public array getDBRef ( array $ref ) //获取一个外键关联
    public array getIndexInfo ( void ) //获取索引信息
    public string getName ( void ) //获取当前集合名称
    public array group ( mixed $keys , array $initial , MongoCode $reduce [, array $options = array() ] ) //分组
    public mixed insert ( array $a [, array $options = array() ] ) //插入数据
    public mixed remove ( array $criteria [, array $options = array() ] ) //删除数据
    public mixed save ( array $a [, array $options = array() ] ) //保存数据
    public string __toString ( void )
    public boolean update ( array $criteria , array $newobj [, array $options = array() ] ) //更新数据
    public array validate ([ bool $scan_data = FALSE ] ) //
}

implements Iterator {
    /* Static Fields */
    static boolean $slaveOkay = FALSE ;
    static integer $timeout = 20000 ;
    /* Methods */
    public MongoCursor addOption ( string $key , mixed $value )
    public MongoCursor batchSize ( int $num )
    __construct ( resource $connection , string $ns [, array $query = array() [, array $fields = array() ]] )
    public int count ([ boolean $foundOnly = FALSE ] )
    public array current ( void ) //返回当天文档
    public boolean dead ( void )
    protected void doQuery ( void )
    public array explain ( void ) //查询执行的细节
    public MongoCursor fields ( array $f ) //返回的列设置
    public array getNext ( void ) //获取下一个文档
    public boolean hasNext ( void ) //是否有下一个文档
    public MongoCursor hint ( array $key_pattern )
    public MongoCursor immortal ([ boolean $liveForever = true ] )
    public array info ( void ) //获取结果游标心底
    public string key ( void ) //获取当前行的_id
    public MongoCursor limit ( int $num ) //限制返回结果行数
    public void next ( void ) //游标移动到下一个文档
    public void reset ( void ) //重设游标
    public void rewind ( void ) //游标移动到第一个文档
    public MongoCursor skip ( int $num ) //跳过指定数量的文档
    public MongoCursor slaveOkay ([ boolean $okay = true ] )
    public MongoCursor snapshot ( void ) //快照
    public MongoCursor sort ( array $fields ) //排序
    public MongoCursor tailable ([ boolean $tail = true ] )
    public MongoCursor timeout ( int $ms )
    public boolean valid ( void )
}

类型

MongoId {
    public string $$id = NULL ;
    /* Methods */
    __construct ([ string $id = NULL ] )
    publicstaticstring getHostname ( void )
    public int getInc ( void )
    public int getPID ( void )
    public int getTimestamp ( void )
    publicstaticMongoId __set_state ( array $props )
    public string __toString ( void )
}

MongoCode {
    /* Methods */
    __construct ( string $code [, array $scope = array() ] )
    public string __toString ( void )
}

MongoDate {
    /* Fields */
    public int $sec ;
    public int $usec ;
    /* Methods */
    __construct ([ long $sec [, long $usec ]] )
    publicstring __toString ( void )
}

MongoRegex {
    /* Fields */
    public string $regex ;
    public string $flags ;
    /* Methods */
    __construct ( string $regex )
    public string __toString ( void )
}

MongoBinData {
    /* Constants */
    const int MongoBinData::FUNC = 1 ;
    const int MongoBinData::BYTE_ARRAY = 2 ;
    const int MongoBinData::UUID = 3 ;
    const int MongoBinData::MD5 = 5 ;
    const int MongoBinData::CUSTOM = 128 ;
    /* Fields */
    public string $bin ;
    public int $type = 2 ;
    /* Methods */
    public __construct ( string $data [, int $type ] )
    public string __toString ( void )
}

MongoInt32 {
    /* Methods */
    public __construct ( string $value )
    public __toString ( void )
}

MongoInt64 {
    /* Methods */
    public __construct ( string $value )
    public __toString ( void )
}

MongoDBRef {
    /* Methods */
    public static array create ( string $collection , mixed $id [, string $database ] )
    public static array get ( MongoDB $db , array $ref )
    public static boolean isRef ( mixed $ref )
}

MongoMinKey {
}

MongoMaxKey {
}

MongoTimestamp {
    /* Fields */
    public int $sec = 0 ;
    public int $inc = 0 ;
    /* Methods */
    __construct ([ long $sec [, long $inc ]] )
    publicstring __toString ( void )
}





豫ICP备09035262号-1