> 백엔드 개발 > PHP7 > 본문

매우 유용한 php7+mongodb 클래스를 공유하세요!

藏色散人
풀어 주다: 2023-02-18 08:30:01
앞으로
1963명이 탐색했습니다.

프로젝트 필요로 인해 프로젝트가 외국인 친구들의 기여로 php7。但是升级了之后发现mongo扩展不能用了。php7.0以上只支持mongodb扩展了。而mongodb扩展的驱动使用起来比monmgo扩展显得很复杂,啰嗦。在网上找了很久。终于找到了一个比较简洁的mongodb类。语法跟mongo的差不多。清晰,自然。

项目地址https://github.com/mongodb/mongo-php-library

으로 업그레이드되었습니다. 그래서 읽을 수 있는 명확한 문서가 없습니다. 다음은 일반적으로 사용되는 몇 가지 방법입니다.

인스턴스 가져오기
$uri = "mongodb://username:password@host/database";
$client = new \MongoDB\Client($uri);
로그인 후 복사
컬렉션 가져오기
$collection = $client->selectCollection('test','test');
로그인 후 복사
단일 데이터 가져오기
$data = $collection->findOne(['id'=>1]);
로그인 후 복사
여러 데이터 가져오기
$where = ['type'=>1];
$options = array(
    'projection' => array('id' => 1, 'age' => 1, 'name' => -1), // 指定返回哪些字段 1 表示返回 -1 表示不返回
    'sort' => array('id' => -1), // 指定排序字段
    'limit' => 10, // 指定返回的条数
    'skip' => 0, // 指定起始位置
);
$data = $collection->find($where,$options)->toArray();
var_dump($data);
로그인 후 복사
중복 제거
$fileName = 'name';
$where = ['id' => ['$lt' => 100]]
$ret = $this->collection->distinct($fileName,$where);
로그인 후 복사
단일 데이터 삽입
$data = array(
    'id' => 2,
    'age' => 20,
    'name' => '张三'
);
$ret = $collection->insertOne($data);
$id=$ret->getInsertedId();
로그인 후 복사
일괄 삽입
$data = array(
    ['id' => 1, 'age' => 21, 'name' => '1xiaoli'],
    ['id' => 2, 'age' => 22, 'name' => '2xiaoli'],
    ['id' => 3, 'age' => 23, 'name' => '3xiaoli'],
    ['id' => 4, 'age' => 26, 'name' => '4xiaoli'],
    ['id' => 5, 'age' => 24, 'name' => '5xiaoli'],
    ['id' => 6, 'age' => 25, 'name' => '6xiaoli'],
);
$ret = $collection->insertMany($data);
# 返回插入id
var_dump($ret->getInsertedIds());
로그인 후 복사
일괄 업데이트
$ret = $collection->updateOne(array('id' => 2), array('$set' => array('age' => 56)));
로그인 후 복사
여러 조각 업데이트
$ret = $collection->updateMany(array('id' => ['$gt' => 1]), array('$set' => array('age' => 56, 'name' => 'x')));
로그인 후 복사
하나 삭제
$ret = $collection->deleteOne(array('id' => 2));
로그인 후 복사
여러 조각 삭제
$collection->deleteMany(array('id' => array('$in' => array(1, 2))));
로그인 후 복사
Aggregation
$ops = [
    [
        '$match' =>['type'=>['$in'=>[2,4]]]
    ],
    [
        '$sort' => ['list.create_time' => -1]  //sort顺序不能变,否则会造成排序混乱,注意先排序再分页
    ],
    [
        '$skip' => 0
    ],
    [
        '$limit' => 20000
    ],
];
$data = $collection->aggregate($ops);
foreach ($data as $document)
{
    var_dump($document);
}
로그인 후 복사

권장: "PHP7 Tutorial"

위 내용은 매우 유용한 php7+mongodb 클래스를 공유하세요!의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:segmentfault.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!