原文链接: http://www.zhaokeli.com/article/8574.html

MongoDb原生操作

Mongodb连接

PHP7 连接 MongoDB 语法如下:

复制代码

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

插入数据

将 name 为"自学教程" 的数据插入到 test 数据库的 runoob 集合中。

复制代码

$bulk = new MongoDB\Driver\BulkWrite;
$document = ['_id' => new MongoDB\BSON\ObjectID, 'name' => '菜鸟教程'];
 
$_id= $bulk->insert($document);
 
var_dump($_id);
 
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");  
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('test.runoob', $bulk, $writeConcern);

读取数据

复制代码

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");  
 
// 插入数据
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1, 'name'=>'baidu', 'url' => 'http://www.baidu.com']);
$bulk->insert(['x' => 2, 'name'=>'Google', 'url' => 'http://www.google.com']);
$bulk->insert(['x' => 3, 'name'=>'taobao', 'url' => 'http://www.taobao.com']);
$manager->executeBulkWrite('test.sites', $bulk);
 
$filter = ['x' => ['$gt' => 1]];
$options = [
    'projection' => ['_id' => 0],
    'sort' => ['x' => -1],
];
 
// 查询数据
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery('test.sites', $query);
 
foreach ($cursor as $document) {
    print_r($document);
}

更新数据

复制代码

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->update(
    ['x' => 2],
    ['$set' => ['name' => '菜鸟工具', 'url' => 'tool.runoob.com']],
    ['multi' => false, 'upsert' => false]
);
 
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");  
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('test.sites', $bulk, $writeConcern);

删除数据

复制代码

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->delete(['x' => 1], ['limit' => 1]);   // limit 为 1 时,删除第一条匹配数据
$bulk->delete(['x' => 2], ['limit' => 0]);   // limit 为 0 时,删除所有匹配数据
 
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");  
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('test.sites', $bulk, $writeConcern);

MongoDB官方操作库

看完上面的CURD操作是不是感觉有点懵逼,操作方式跟想像中的完全不一样,可能官方也想到啦这一块,于是又封装啦一个操作库让大家使用。文档地址如下

https://docs.mongodb.com/php-library/current/tutorial/crud/

安装

复制代码

composer require mongodb/mongodb

添加数据

插入单条数据

在数据库test中的users集合中插入数据,如果数据库或集合不存在则会自动创建

复制代码

$collection      = (new MongoDB\Client)->test->users;
$insertOneResult = $collection->insertOne([
    'username' => 'admin',
    'email'    => 'admin@example.com',
    'name'     => 'Admin User',
]);
printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount());
var_dump($insertOneResult->getInsertedId());

输出结果

数据库中数据

可以看出返回$oid为数据库自动分配的唯一标识,如果我们插入的时候传入id值的话,mongodb会判断这个id是否存在,如果存在就会报错,如果不存在则直接返回传入的id值

复制代码

$collection      = (new MongoDB\Client)->test->users;
$insertOneResult = $collection->insertOne(['_id' => 1, 'name' => 'Alice']);
printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount());
var_dump($insertOneResult->getInsertedId());

执行结果

插入多条数据

复制代码

$collection = (new MongoDB\Client)->test->users;
$insertManyResult = $collection->insertMany([
    [
        'username' => 'admin',
        'email' => 'admin@example.com',
        'name' => 'Admin User',
    ],
    [
        'username' => 'test',
        'email' => 'test@example.com',
        'name' => 'Test User',
    ],]);
printf("Inserted %d document(s)\n", $insertManyResult->getInsertedCount());
var_dump($insertManyResult->getInsertedIds());

查询数据

如果要使用id查询,则需要使用下面的ObjectId类来封装下传进去

使用自增id查询

复制代码

$collection = (new MongoDB\Client)->test->users;
$id         = new \MongoDB\BSON\ObjectId('5cecd708ab4e4536fc0076e2');
$document   = $collection->findOne(['_id' => $id]);
var_dump($document);

其它条件查询

使用其它条件数据则直接传进去就可以

复制代码

$collection = (new MongoDB\Client)->test->users;
$document   = $collection->findOne(['username' => 'admin']);
var_dump($document);

使用limit,sort,skip查询

默认情况下是返回所有的字段数据,也可以指定字段返回,limit是返回的行数,sort是使用name字段-1为降序,1为升序,skip为跳过前多少条数据如下

复制代码

$collection = (new MongoDB\Client)->test->users;
$cursor     = $collection->find(
    [
        'username' => 'admin',
    ],
    [
        'projection' => [
            'email' => 1,
        ],
        'limit'      => 4,
        'sort'       => ['name' => -1],
        'skip'       =>1,
    ]);
foreach ($cursor as $restaurant) {
    var_dump($restaurant);
}

正则条件查询

复制代码

$collection = (new MongoDB\Client)->test->users;
$cursor     = $collection->find(
    [
        'username' => new MongoDB\BSON\Regex('^ad', 'i'),
    ],
    [
        'projection' => [
            'email' => 1,
        ],
        'limit'      => 1,
        'sort'       => ['pop' => -1],
    ]);
foreach ($cursor as $restaurant) {
    var_dump($restaurant);
}

另外一种正则式的写法

复制代码

$collection = (new MongoDB\Client)->test->users;
$cursor     = $collection->find(
    [
        'username' => ['$regex' => '^ad', '$options' => 'i'],
    ],
    [
        'projection' => [
            'email' => 1,
        ],
        'limit'      => 1,
        'sort'       => ['pop' => -1],
    ]);
foreach ($cursor as $restaurant) {
    var_dump($restaurant);
}

查询多个数据

复制代码

$collection = (new MongoDB\Client)->test->users;
$cursor     = $collection->find(['username' => 'admin']);
foreach ($cursor as $document) {
    echo $document['_id'], "\n";
}

更新数据

更新单条数据

复制代码

$collection   = (new MongoDB\Client)->test->users;
$updateResult = $collection->updateOne(
    ['username' => 'admin'],
    ['$set' => ['name' => 'new nickname']]
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());

更新多条数据

复制代码

$collection   = (new MongoDB\Client)->test->users;
$updateResult = $collection->updateMany(
    ['username' => 'admin'],
    ['$set' => ['name' => 'new nickname']]
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());

替换文档

替换文档其它跟更新数据类似,但是这个操作不会修改id,如下

复制代码

$collection   = (new MongoDB\Client)->test->users;
$updateResult = $collection->replaceOne(
    ['username' => 'admin'],
    ['username' => 'admin2', 'name' => 'new nickname']
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());

Upsert操作

这个名字应该是个缩写,更新或替换操作时如果有匹配的数据则直接操作,如果没有匹配的数据则插入一条新数据,意思是如果更新或替换操作的第三个参数如果传 'upsert'=>True 的话就可以开启这个功能

复制代码

$collection   = (new MongoDB\Client)->test->users;
$updateResult = $collection->updateOne(
    ['username' => 'admin3'],
    ['$set' => ['username' => 'admin2', 'name' => 'new nickname']],
    ['upsert' => true]
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
printf("Upserted %d document(s)\n", $updateResult->getUpsertedCount());
$upsertedDocument = $collection->findOne([
    '_id' => $updateResult->getUpsertedId(),
]);
var_dump($upsertedDocument);

如果有匹配的情况下最后输出为NULl

没有匹配的情况下最后输出插入的数据

删除数据

复制代码

$collection   = (new MongoDB\Client)->test->users;
$deleteResult = $collection->deleteOne(['username' => 'admin3']);
printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount());
$deleteResult = $collection->deleteMany(['username' => 'admin2']);
printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount());

PHP7 MongoDB 使用方法的更多相关文章

  1. MongoDB基本方法

    一.MongoDB Limit与Skip方法 MongoDB Limit() 方法 如果你需要在MongoDB中读取指定数量的数据记录,可以使用MongoDB的Limit方法,limit()方法接受一 ...

  2. 落网数据库简单查询接口 caddy+php7+mongodb

    落网数据库简单查询接口 一个简单的DEMO,使用了caddy + php7 + mongodb 数据库&接口设计 来自 https://github.com/Aedron/Luoo.spide ...

  3. windows2012 下面php7.2 安装mongodb4.0.4的扩展以及操作mongodb的方法

    php连接mongodb驱动 的下载页面http://pecl.php.net/package/mongodb 数据插入: $manager = new MongoDB\Driver\Manager( ...

  4. ubuntu中搭建php7+mongodb方法

    首先照着这篇文章操作 http://blog.csdn.net/Toshiya14/article/details/51417076 结果发现一直报Cannot find OpenSSL's libr ...

  5. 推荐一个php7+ mongodb三方类

      373 次阅读  ·  读完需要 8 分钟 5 由于项目需要,把项目升级到了php7.但是升级了之后发现mongo扩展不能用了.php7.0以上只支持mongodb扩展了.而mongodb扩展的驱 ...

  6. nodejs连接mongodb的方法

    一. var express = require('express'); var mongodb = require('mongodb'); var app = express(); app.use( ...

  7. C# 访问MongoDB 通用方法类

    using MongoDB.Driver; using System; namespace MongoDBDemo { public class MongoDb { public MongoDb(st ...

  8. MongoDB 备份方法

    翻译自 http://docs.mongodb.org/manual/core/backups/ 有以下几种方法来备份MongoDB群集: 通过复制底层数据文件来备份 通过mongodump来备份 通 ...

  9. springdata整合mongodb一些方法包括or,and,regex等等《有待更新》

    这几天接触mongodb以及springdata,自己英语比较戳,所以整理这些方法花的时间多了点,不过也是我第一次在外国网站整理技术 不多说,直接上代码,这里只是给出一些操作方法而已,如果有需要源码的 ...

随机推荐

  1. goroutine的使用与常见错误

    goroutine的使用时常见错误 goroutine是Golang 的核心之一,在使用时,一般都要配合channel一起使用. 在使用时,经常会遇到一些错误,包括: 不输出 输出与希望输出不一致 a ...

  2. com.mysql.jdbc.Driver not loaded. Are you sure you've included the correct jdbc driver in :jdbc_driver_library?

    把对应的jdbc jar包放到 /usr/share/logstash/logstash-core/lib/jars/路径 下即可.可以在配置文件不用配置驱动库.

  3. Java内存模型、JVM内存结构和Java对象模型

    JVM内存结构 我们都知道,Java代码是要运行在虚拟机上的,而虚拟机在执行Java程序的过程中会把所管理的内存划分为若干个不同的数据区域,这些区域都有各自的用途.其中有些区域随着虚拟机进程的启动而存 ...

  4. vue之获取原生的dom的方式

    1.获取原生的DOM的方式 <!DOCTYPE html> <html lang="en"> <head> <meta charset=& ...

  5. Django之路——5 Django的模板层

    你肯能已经注意到我们在例子视图中返回文本的方式有点特别. 也就是说,HTML被直接硬编码在 Python代码之中. def current_datetime(request): now = datet ...

  6. 正确理解cookie和session机制原理

    php中cookie和session是我们常用的两个变量了,一个是用户客户端的,一个用在服务器的但他们的区别与工作原理怎么样,下面我们一起来看看cookie和session机制原理吧. cookie和 ...

  7. TCP/IP 协议栈及 OSI 参考模型详解

    OSI参考模型 OSI RM:开放系统互连参考模型(open systeminterconnection reference model) OSI参考模型具有以下优点: 简化了相关的网络操作: 提供设 ...

  8. Eclipse中修改了项目,导入Tomcat中时,括号显示原来项目的名字

    Eclipse中Tomcat导入项目并且修改了项目名字,把项目添加到Tomcat上,发现在项目后面带了个括号里面显示原来项目的名字,并且在访问的时候也只能用原来的项目名访问,怎么办呢? 1.打开你的项 ...

  9. python - django (创建到运行流程)

    a = 0 """ 1. 创建 Django 操作文件 a. cmd 中选择路径: cd C:\Users\ad\PycharmProjects\index\1\文件名 ...

  10. jquery手机触屏滑动拼音字母城市选择器代码

    今天用到城市选择,直接用拼音滑动方式来选择,用的时候引入jquery(个别样式需要自己修改) <div class="yp_indz"><img src=&quo ...