PHP Simple manipulation of mongodb database sample using mongoclient

  • 2021-11-24 01:00:43
  • OfStack

This article illustrates the simple operation of mongodb database by PHP using mongoclient. Share it for your reference, as follows:

It's better to go back to the advanced section of mongodb shell Basic Command, and look at the content here again, otherwise I will talk about some things in a general way.

Ok, don't talk nonsense, post the code directly, don't be afraid to look at the code, basically every line has written comments


<!-- 
1 In this paper, the mongoClient Class to implement the mongodb Simple operation of, 
2 , need to be familiar with in advance. " mongodb Basic commands-advanced articles " 
3 Where the Update Data section only shows 1 A $set But with the operation command is 1 Like, pay attention to understanding and trying 
4 At the bottom, there is a brief introduction to functions, in which 1 Some content will be added after I have studied the following chapters 
 -->


<?php
try {
  // 连接mongodb数据库
  $mongo = new MongoClient();
  // 选择数据库
  $db_name=$mongo->test;
  // 或者这样也可以
  // $db_name=$mongo->selectDB('test');
  // 选择集合
  $collection_name=$db_name->student;
  // 或者和上面1样
  // $collection_name=$$db_name->selectCollection('collection_name');
  echo '<pre>';
  // 查看全部dbs
  $dbs=$mongo->listDBs();
  // var_dump($dbs);
  $collections=$db_name->listCollections();
  // var_dump($collections);
  // 定义被插入的数据,而且php的数组形式与json格式类似,所以很容易理解
  $input = array(
   'name' =>'yang' ,
   'sex'=>'man',
   'sorce' => array(
   'math' =>60 ,
   'pe'=>30 
   )
   );
  // 插入数据,$result会显示插入数据的结果
  // insert的第2个参数内容请看--函数1
  // $result=$collection_name->insert($input);
  // var_dump($result);
  // 查询单条数据,跟shell命令里的findOne()1样
  $findOne=$collection_name->findOne();
  // var_dump($findOne);
  // 查找全部数据,记住1点,find()函数的返回值不是跟findOne()函数1样的数组。而是1个对象,所以不能直接
  // 打印出来,至于如何读取其中的内容,可以使用foreach循环
  $find=$collection_name->find();
  // 可以跟mongo shell中1样为find()函数传递第1个筛选参数
  $situation = array(
   'name' => 'yang', 
   );
  // 选择返回的字段内容
  $field = array('sorce' => 1 );
  // 详细解释看--函数2
  $find=$collection_name->find($situation,$field);
  // while ($each=$find->getNext()) {
  // var_dump($each);
  // }
  $sort=$collection_name->find()->sort(array('math' => -1, ));
  $limit=$collection_name->find()->sort(array('math' => -1, ))->limit(2);
  $skip=$collection_name->find()->sort(array('math' => -1, ))->skip(2);
  $count=$collection_name->find()->sort(array('math' => -1, ))->count();
  // echo $count;
  // foreach ($skip as $value) {
  // var_dump($value);
  // }
  // 条件操作符的使用
  $situation2=array(
   // 注意这里字段的设置跟shell中1样
   'item.quantity'=>array('$gt'=>5)
   );
  $gt=$db_name->orders->find($situation2);
  /**********************************************数据的更新*******************************************/
  // 注意,接下来这段代码会更新整个匹配到的文档,就跟update没有使用$set1样
  // 详情查看函数3
  $update=$db_name->orders->update(
   array('_class'=>'com.mongo.model.Orders'),
   array('_class'=>'hello world')
   );
  // 注意$set的位置,是不是与shell命令中1致
  $update=$db_name->orders->update(
   array('_class'=>'com.mongo.model.Orders'),
   array('$set'=>array('_class'=>'hello world'))
   );
  // 从这里可以看到,如果会shell命令的话,那么这1节的重点就是将shell命令与php数组之间的相互转化了
  /**********************************************数据的删除*******************************************/
  // 删除集合中的数据
  $remove=$db_name->orders->remove(array('_class'=>'com.mongo.model.Orders'));
  // 删除整个集合
  $db_name->orders->drop();
  // 本来还有1些集合之间使用DBRef联查以及GRidFS的内容的,但是那个还是等以后要用了再来补充好了
} catch (MongoConnectionException $e) {
  echo $e->getMessage();
}
?>

Explanation of several functions

-----------------------------

Insert data function insert


$mongo->$db_name->$collection_name->insert($input.$options)

Parameters and default values in $option


$option=array(
'fsync'=> false,
'j'  => false,
'w'  => 1,
'wtimeout'=>10000,
'timeout'=>10000
)

'fsync'

When this parameter is set to true, php will tell mongodb to write the currently written data directly to the hard disk, even though not all of it has been written from the php document to the mongodb database

'j'

If this parameter is set to True, php will tell mongodb to log this modification before the data insertion succeeds

'w'

If it is set to 0, the write operation will not be confirmed, which will not be discussed here

'wtimeout'

Used by binding with 'w' above, which will be described later

'timeout'

The timeout time that the client waits for the server to respond, that is, if the server of php waits for the mongodb database to write data, if it exceeds the time specified by timeout, even if the writing fails this time

------------------------------

Filter data function find


$mongo->$db_name->$collection_name->find($situation,$field)

$situation can be null to return all data, or an array to indicate filters, just like mongodb command 1
$field can also be null, indicating that all fields are returned, or it can be passed into an array like the first parameter 1, specifying the returned fields

Note that the _ id field is returned automatically even though the $field limit is used above

--------Function 3----------

Update data update


$mongo->$db_name->$collection_name->update($criteria,$update,$option)

It is easy to understand in combination with shell command
$criteria denotes filtered documents for updates
$update is the data to be updated


$option=array(
'upsert'=>false,
'multiple'=>true,
'fsync'=>false,
'w'=>1,
'wtimeout'=>10000,
'timeout'=>10000
)

The functions of the latter are described in Function 1, so we will not repeat them here. upsert is true, which means that if the current document exists, it will be updated, and if it does not exist, it will be created. multiple is true, which means that all documents matching this condition will be updated, that is, more than one document meeting the condition will be updated.

--------Function 3----------

Delete data remove


$mongo->$db_name->$collection_name->remove($remove,$option)

$remove represents the same as find() Filter criteria for the first parameter 1 sample


$option=array(
'justOne'=>false,
'fsync'=>false,
'w'=>1,
'j'=>false,
'wtimeout'=>10000,
'timeout'=>10000
)

I will not repeat the above, justOne according to the name, just one, if it is true, delete one document matching $remove

For more readers interested in PHP related contents, please check the topics of this site: "PHP+MongoDB Database Operation Skills Encyclopedia", "PHP Database Operation Skills Summary Based on pdo", "php Object-Oriented Programming Introduction Tutorial", "php String (string) Usage Summary", "php+mysql Database Operation Introduction Tutorial" and "php Common Database Operation Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: