php中的mongodb select常用操作代码示例(2)


$result = $collection->find()->fields(array("auther"=>false,"money"=>false));    //不显示auther和money列 
 
$result = $collection->find()->fields(array("title"=>true));      //只显示title列 
 
/**
 *money在60到100之间,typecolumn和money二列必须存在
 */ 
$where=array('typeColumn'=>array('$exists'=>true),'money'=>array('$exists'=>true,'$gte'=>60,'$lte'=>100)); 
$result = $collection->find($where); 

5、分页

复制代码 代码如下:


> db.books.find().skip(1).limit(1);  //跳过第条,取一条 
{ "_id" : 2, "title" : "围城", "auther" : "钱钟书", "typeColumn" : "test", "money" : 56, "code" : 20 } 

这根mysql,limit,offset有点类似,php代码如下:

复制代码 代码如下:


$result = $collection->find()->limit(1)->skip(1);//跳过 1 条记录,取出 1条 

6、排序

复制代码 代码如下:


> db.books.find().sort({money:1,code:-1});    //1表示降序 -1表示升序,参数的先后影响排序顺序  
{ "_id" : 3, "title" : "朝发白帝城", "auther" : "李白", "typeColumn" : "test", "money" : 30, "code" : 30 } 
{ "_id" : 2, "title" : "围城", "auther" : "钱钟书", "typeColumn" : "test", "money" : 56, "code" : 20 } 
{ "_id" : 1, "title" : "红楼梦", "auther" : "曹雪芹", "typeColumn" : "test", "money" : 80, "code" : 10 } 
{ "_id" : 4, "title" : "将近酒", "auther" : "李白", "money" : 90, "code" : 40 }

php代码如下:

复制代码 代码如下:


$result = $collection->find()->sort(array('code'=>1,'money'=>-1)); 

7、模糊查询

复制代码 代码如下:


> db.books.find({"title":/城/});      //like '%str%' 糊查询集合中的数据 
{ "_id" : 2, "title" : "围城", "auther" : "钱钟书", "typeColumn" : "test", "money" : 56, "code" : 20 } 
{ "_id" : 3, "title" : "朝发白帝城", "auther" : "李白", "typeColumn" : "test", "money" : 30, "code" : 30 } 
 
> db.books.find({"auther":/^李/});    //like 'str%' 糊查询集合中的数据 
{ "_id" : 3, "title" : "朝发白帝城", "auther" : "李白", "typeColumn" : "test", "money" : 30, "code" : 30 } 
{ "_id" : 4, "title" : "将近酒", "auther" : "李白", "money" : 90, "code" : 40 } 
 
> db.books.find({"auther":/书$/});   //like '%str' 糊查询集合中的数据 
{ "_id" : 2, "title" : "围城", "auther" : "钱钟书", "typeColumn" : "test", "money" : 56, "code" : 20 } 
 
> db.books.find( { "title": { $regex: '城', $options: 'i' } } );   //like '%str%' 糊查询集合中的数据 
{ "_id" : 2, "title" : "围城", "auther" : "钱钟书", "typeColumn" : "test", "money" : 56, "code" : 20 } 
{ "_id" : 3, "title" : "朝发白帝城", "auther" : "李白", "typeColumn" : "test", "money" : 30, "code" : 30 } 

php代码如下,按顺序对应的:

复制代码 代码如下:


$param = array("title" => new MongoRegex('/城/')); 
$result = $collection->find($param); 
 
$param = array("auther" => new MongoRegex('/^李/')); 
$result = $collection->find($param); 
 
$param = array("auther" => new MongoRegex('/书$/')); 
$result = $collection->find($param); 

8、$in和$nin

复制代码 代码如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/c369b15f6c36943712ef5717b3140d77.html