찾다
php教程php手册php中的mongodb select常用操作代码示例,mongodbselect

php中的mongodb select常用操作代码示例,mongodbselect

前面说到了mongodb安装,配置,集群,以及php的插入与更新等,请参考:mongodb。
下面说一下,mongodb select的常用操作

测试数据:

复制代码 代码如下:


{ "_id" : 1, "title" : "红楼梦", "auther" : "曹雪芹", "typeColumn" : "test", "money" : 80, "code" : 10 } 
{ "_id" : 2, "title" : "围城", "auther" : "钱钟书", "typeColumn" : "test", "money" : 56, "code" : 20 } 
{ "_id" : 3, "title" : "朝发白帝城", "auther" : "李白", "typeColumn" : "test", "money" : 30, "code" : 30 } 
{ "_id" : 4, "title" : "将近酒", "auther" : "李白", "money" : 90, "code" : 40 }

1、取表条数

复制代码 代码如下:


> db.books.count(); 

 
> db.books.find().count(); 

 
> db.books.count({auther: "李白" }); 

 
> db.books.find({money:{$gt:40,$lte:60}}).count(); 

 
> db.books.count({money:{$gt:40,$lte:60}}); 

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

复制代码 代码如下:


$collection->count();             //结果:4 
$collection->find()->count();     //结果:4 
$collection->count(array("auther"=>"李白"));   //结果:2 
$collection->find(array("money"=>array('$gt'=>40,'$lte'=>60)))->count();     //结果:1 
$collection->count(array("money"=>array('$gt'=>40,'$lte'=>60)));    //结果:1 

提示:$gt为大于、$gte为大于等于、$lt为小于、$lte为小于等于、$ne为不等于、$exists不存在、$in指定范围、$nin指定不在某范围

2、取单条数据

复制代码 代码如下:


> db.books.findOne(); 

        "_id" : 1, 
        "title" : "红楼梦", 
        "auther" : "曹雪芹", 
        "typeColumn" : "test", 
        "money" : 80, 
        "code" : 10 

 
> db.books.findOne({auther: "李白" }); 

        "_id" : 3, 
        "title" : "朝发白帝城", 
        "auther" : "李白", 
        "typeColumn" : "test", 
        "money" : 30, 
        "code" : 30 

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

复制代码 代码如下:


$collection->findOne(); 
$collection->findOne(array("auther"=>"李白")); 

3、find snapshot 游标

复制代码 代码如下:


> db.books.find( { $query: {auther: "李白" }, $snapshot: true } ); 
{ "_id" : 3, "title" : "朝发白帝城", "auther" : "李白", "typeColumn" : "test", "money" : 30, "code" : 30 } 
{ "_id" : 4, "title" : "将近酒", "auther" : "李白", "money" : 90, "code" : 40 }

php代码如下:

复制代码 代码如下:


/**
* 注意:
* 在我们做了find()操作,获得 $result 游标之后,这个游标还是动态的.
* 换句话说,在我find()之后,到我的游标循环完成这段时间,如果再有符合条件的记录被插入到collection,那么这些记录也会被$result 获得.
*/ 
$result = $collection->find(array("auther"=>"李白"))->snapshot(); 
foreach ($result as $id => $value) { 
 var_dump($value); 
}

4、自定义列显示

复制代码 代码如下:


> db.books.find({},{"money":0,"auther":0});      //money和auther不显示 
{ "_id" : 1, "title" : "红楼梦", "typeColumn" : "test", "code" : 10 } 
{ "_id" : 2, "title" : "围城", "typeColumn" : "test", "code" : 20 } 
{ "_id" : 3, "title" : "朝发白帝城", "typeColumn" : "test", "code" : 30 } 
{ "_id" : 4, "title" : "将近酒", "code" : 40 } 
 
> db.books.find({},{"title":1});          //只显示title列 
{ "_id" : 1, "title" : "红楼梦" } 
{ "_id" : 2, "title" : "围城" } 
{ "_id" : 3, "title" : "朝发白帝城" } 
{ "_id" : 4, "title" : "将近酒" } 
 
/**
*money在60到100之间,typecolumn和money二列必须存在
*/ 
> db.books.find({money:{$gt:60,$lte:100}},{"typeColumn":1,"money":1}); 
{ "_id" : 1, "typeColumn" : "test", "money" : 80 } 
{ "_id" : 4, "money" : 90 } 

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

复制代码 代码如下:


$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

复制代码 代码如下:


> db.books.find( { money: { $in: [ 20,30,90] } } );   //查找money等于20,30,90的数据 
{ "_id" : 3, "title" : "朝发白帝城", "auther" : "李白", "typeColumn" : "test", "money" : 30, "code" : 30 } 
{ "_id" : 4, "title" : "将近酒", "auther" : "李白", "money" : 90, "code" : 40 } 
 
> db.books.find( { auther: { $in: [ /^李/,/^钱/ ] } } );    //查找以李,钱开头的数据 
{ "_id" : 2, "title" : "围城", "auther" : "钱钟书", "typeColumn" : "test", "money" : 56, "code" : 20 } 
{ "_id" : 3, "title" : "朝发白帝城", "auther" : "李白", "typeColumn" : "test", "money" : 30, "code" : 30 } 
{ "_id" : 4, "title" : "将近酒", "auther" : "李白", "money" : 90, "code" : 40 }

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

复制代码 代码如下:


$param = array("money" => array('$in'=>array(20,30,90))); 
$result = $collection->find($param); 
foreach ($result as $id=>$value) { 
 var_dump($value); 

 
$param = array("auther" => array('$in'=>array(new MongoRegex('/^李/'),new MongoRegex('/^钱/')))); 
$result = $collection->find($param); 
foreach ($result as $id=>$value) { 
 var_dump($value); 
}

9、$or

复制代码 代码如下:


> db.books.find( { $or: [ { money: 20 }, { money: 80 } ] } );   //查找money等于20,80的数据 
{ "_id" : 1, "title" : "红楼梦", "auther" : "曹雪芹", "typeColumn" : "test", "money" : 80, "code" : 10 } 

php代码如下:

复制代码 代码如下:


$param = array('$or'=>array(array("money"=>20),array("money"=>80))); 
$result = $collection->find($param); 
foreach ($result as $id=>$value) { 
 var_dump($value); 
}

10、distinct

复制代码 代码如下:


> db.books.distinct( 'auther' ); 
[ "曹雪芹", "钱钟书", "李白" ] 
 
> db.books.distinct( 'auther' , { money: { $gt: 60 } }); 
[ "曹雪芹", "李白" ] 

php代码如下:

复制代码 代码如下:


$result = $curDB->command(array("distinct" => "books", "key" => "auther")); 
foreach ($result as $id=>$value) { 
 var_dump($value); 

 
$where = array("money" => array('$gte' => 60)); 
$result = $curDB->command(array("distinct" => "books", "key" => "auther", "query" => $where)); 
foreach ($result as $id=>$value) { 
 var_dump($value); 
}

先写到这儿,上面只是SELECT的一些常用操作,接下来,还会写一点。

php操作mongoDB数据库查询的时怎写“或”这样的多个条件查询代码?

据我所知,目前mongoDB没有“或”这个东西

但我刚才在网上查了下
发现了下面的信息,你参考下吧

在mongodb中有$or 操作符的,官网中给出的例子如下:

Simple:

db.foo.find( { $or : [ { a : 1 } , { b : 2 } ] } )

With another field

db.foo.find( { name : "bob" , $or : [ { a : 1 } , { b : 2 } ] } )

The $or operator retrieves matches for each or clause individually and eliminates duplicates when returning results. A number of $or optimizations are planned for 1.8. See this thread for details.
$or cannot be nested.
 

PHP中怎实现一个select语句读出多个表的内容

复合查询?例如。详细的意思不用我解说了吧
$sql="select * from p_newsbase as a, p_newscontent as b where a.id=b.nid and a.id='$_GET[id]'"
 

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.