本文主要是介绍tp6 mongodb简单的增删改查,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
controller/mongo.php
<?phpnamespace app\controller;
use think\facade\Db;
class Mongo
{/*** 插入数据* */public function insert(){// 插入数据$data = ['name' => 'zhangsan','email' => 'zhangsan@example.com','children' => ['_id' => 1,'name' => "Child 2"]];$res = Db::name('test')->insert($data);dd($res);}/*** 批量插入数据* */public function insertAll() {$data = [['name' => 'John','email' => 'john@example.com','addr' => ['city' => 'New York','state' => 'NY','zip' => '10001']],['name' => 'Jane','email' => 'jane@example.com','addr' => ['city' =>'Los Angeles','state' => 'CA','zip' => '90001']]];$res = Db::name('test')->insertAll($data);dd($res);}/*** 查询数据* */public function find() {//严格区分字符串和数字类型//按照条件查询,查询单个$res = Db::name('test')->where('name', 'John')->find();$res1 = Db::name('test')->where('name', 'John')->select();//根据_id查询$res2 = Db::name('test')->where('_id', '661602b5203500009e0060c3')->find();//根据_id in 查询$res3 = Db::name('test')->where('_id', 'in', ['661602b5203500009e0060c3', '661603a2203500009e0060c4'])->select();//使用子文档查询$res4 = Db::name('test')->where('addr.city', 'New York')->select();//使用子文档查询,子文档是一个多维数组$res5 = Db::name('test')->where('children.1._id', 1)->select();dd($res5);}/*** 更新数据* */public function update() {//更新单个$res = Db::name('test')->where('name', 'John')->update(['email' => 'john@example.com1']);//更新多个$res1 = Db::name('test')->where('name', 'John')->update(['email' => 'john@example.com1']);//根据_id更新$res2 = Db::name('test')->where('_id', '661602b5203500009e0060c3')->update(['email' =>'john@example.com1']);dd(1);}/*** 删除数据* */public function delete() {//删除单个$res = Db::name('test')->where('name', 'John')->delete();//删除多个$res1 = Db::name('test')->where('name', 'John')->delete();//根据_id删除$res2 = Db::name('test')->where('_id', '661602b5203500009e0060c3')->delete();dd(1);}/*** 聚合查询* */public function aggregate() {//简单查询$count = Db::connect('mongo')->table('test')->count();//单个条件查询$count1 = Db::connect('mongo')->table('test')->where('name', 'zhangsan')->count();}
}
config/database.php
'mongo' => [// 数据库类型'type' => 'mongo',// 设置MongoDB的主机地址'hostname' => '127.0.0.1',// 设置MongoDB的端口'hostport' => '27017',// 设置MongoDB的数据库名'database' => 'test',// 是否是复制集'is_replica_set' => false,// 用户名'username' => '',// 密码'password' => '',// MongoDB连接的其它选项'options' => [],// 设置MongoDB的连接参数'uri_options' => [],],
route/app.php
//mongo
Route::post('mongo/insert', 'mongo/insert');
Route::post('mongo/insertAll', 'mongo/insertAll');
Route::post('mongo/find', 'mongo/find');
Route::post('mongo/delete', 'mongo/delete');
Route::post('mongo/aggregate', 'mongo/aggregate');
这篇关于tp6 mongodb简单的增删改查的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!