山间小道 發表於 2020-7-28 23:54:00

PHP7操作MongoDB

<p></p><div class="toc"><div class="toc-container-header">目录</div><ul><li>插入数据</li><li>查询数据</li><li>更新数据</li><li>删除数据</li></ul></div><p></p>
<p>PHP7里面使用如下库,操作比较复杂</p>
<p><img src="https://img2020.cnblogs.com/blog/720430/202007/720430-20200728235215449-1537858136.png" alt="" loading="lazy"></p>
<p>PHP7连接MongoDB语法如下:</p>
<pre><code class="language-php">//参数规则: mongodb://账号:密码@IP:端口/数据库
$manager = new \MongoDB\Driver\Manager("mongodb://php:123456@localhost:27017/php");
</code></pre>
<h3 id="插入数据">插入数据</h3>
<pre><code class="language-php">//1.连接MongoDB
$manager = new \MongoDB\Driver\Manager("mongodb://php:123456@localhost:27017/php");

//2.创建一个BulkWrite对象
$bulk = new \MongoDB\Driver\BulkWrite();
$bulk-&gt;insert(['name' =&gt; 'bashlog', 'age' =&gt; 26, 'email' =&gt; 'bashlog@foxmail.com']);
$bulk-&gt;insert(['name' =&gt; 'itbsl', 'age' =&gt; 12, 'email' =&gt; 'itbsl@foxmail.com']);

//3.执行插入
$manager-&gt;executeBulkWrite('php.stu', $bulk);
</code></pre>
<p>查看插入情况</p>
<p><img src="https://img2020.cnblogs.com/blog/720430/202007/720430-20200728235234495-960135286.png" alt="" loading="lazy"></p>
<h3 id="查询数据">查询数据</h3>
<pre><code class="language-php">//1.连接MongoDB
$manager = new \MongoDB\Driver\Manager("mongodb://php:123456@localhost:27017/php");

//2.创建一个Query对象
$filter = ['age' =&gt; ['$gt' =&gt; 5]];
$options = [
    'sort' =&gt; ['age' =&gt; -1]
];
$query = new \MongoDB\Driver\Query($filter, $options);
$cursor = $manager-&gt;executeQuery('php.stu', $query);

foreach ($cursor as $document) {
    var_dump($document);
}
</code></pre>
<h3 id="更新数据">更新数据</h3>
<pre><code class="language-php">//1.规则:mongodb://账号:密码@IP:端口/数据库
$manager = new \MongoDB\Driver\Manager("mongodb://php:123456@localhost:27017/php");


//2.创建一个BulkWrite对象
$bulk = new \MongoDB\Driver\BulkWrite();

$bulk-&gt;update(
    ['age' =&gt; 12],
    ['$set' =&gt; ['name' =&gt; 'kitty', 'age' =&gt; 122]],
    ['multi' =&gt; false, 'upsert' =&gt; false]
);

$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager-&gt;executeBulkWrite('php.stu', $bulk, $writeConcern);
</code></pre>
<h3 id="删除数据">删除数据</h3>
<pre><code class="language-php">//1.规则:mongodb://账号:密码@IP:端口/数据库
$manager = new \MongoDB\Driver\Manager("mongodb://php:123456@localhost:27017/php");


//2.创建一个BulkWrite对象
$bulk = new \MongoDB\Driver\BulkWrite();
//limit为1时,删除第一条匹配的数据
//limit为0时,删除所有匹配数据
$bulk-&gt;delete(['age' =&gt; 122], ['limit' =&gt; 1]);

$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager-&gt;executeBulkWrite('php.stu', $bulk, $writeConcern);
</code></pre>
<blockquote>
<p>如果该文章对您有帮助,请您点个<strong>推荐</strong>,感谢。</p>
</blockquote><br><br>
来源:https://www.cnblogs.com/itbsl/p/13394636.html
頁: [1]
查看完整版本: PHP7操作MongoDB