文字

MongoDB::createCollection

(PECL mongo >=0.9.0)

MongoDB::createCollection创建一个集合

说明

public MongoCollection MongoDB::createCollection ( string $name [, array $options ] )

这个方法用于创建一个“有限集合”之类需要特殊参数的集合。它相当于执行

<?php

$collection 
$db -> command (array(
    
"create"  =>  $name ,
    
"capped"  =>  $options [ "capped" ],
    
"size"  =>  $options [ "size" ],
    
"max"  =>  $options [ "max" ],
    
"autoIndexId"  =>  $options [ "autoIndexId" ],
));

?>
参考 MongoDB::command() 了解更多关于数据库指令的信息

参数

name

集合的名字

options

一个数组,包含集合的选项,具有以下形式: array("optionname" => "optionvalue", ...) 。支持的选项跟MongoDB服务器的版本有关。目前支持的选项有:

capped

这个集合是否是固定大小的。

size

如果是固定大小的,指定它的大小(字节)。

max

如果是固定大小的,指定集合中最多存储多少个文档。

autoIndexId

如果 capped 是 TRUE 你可以显式定义为 FALSE 来禁用 自增_id 特性。MongoDB 2.2以前, autoIndexId 的默认值是 FALSE

返回值

返回新建的集合对象。

范例

Example #1 MongoDB::createCollection() 固定大小集合 实例

固定大小(capped)集合是一种磁盘容量或者文档数量固定的特殊集合。当集合“满了”的时候,最老的文档就会被新文档代替。固定大小集合在类似日志记录的应用中非常有用,比如你需要保留一定量的日志,不用担心它们占用过多的空间。

这个例子建立了一个非常小的日志集合,保存10条日志。

<?php

$log 
$db -> createCollection (
    
"logger" ,
    array(
        
'capped'  =>  true ,
        
'size'  =>  10 * 1024 ,
        
'max'  =>  10
    
)
);

for (
$i  0 $i  100 $i ++) {
    
$log -> insert (array( "level"  =>  WARN "msg"  =>  "sample log message # $i " "ts"  => new  MongoDate ()));
}

$msgs  $log -> find ();

foreach (
$msgs  as  $msg ) {
    echo 
$msg [ 'msg' ]. "\n" ;
}

?>

以上例程的输出类似于:


sample log message #90
sample log message #91
sample log message #92
sample log message #93
sample log message #94
sample log message #95
sample log message #96
sample log message #97
sample log message #98
sample log message #99

更新日志

版本 说明
1.4.0

1.4.0以前的版本里,所有选项都是这个方法的参数。之前版本这个方法的签名是这样的:

public MongoCollection MongoDB::createCollection ( string $name [, bool $capped = FALSE [, int $size = 0 [, int $max = 0 ]]] )

参数的意义与现在版本的 options 参数相同。

上一篇: 下一篇: