SoFunction
Updated on 2025-03-09

PHP operation MongoDB implements the function of adding, deleting, modifying and checking [with php7 operation MongoDB method]

This article describes the PHP operation MongoDB to implement the function of adding, deleting, modifying and checking. Share it for your reference, as follows:

MongoDB's PHP driver provides some core classes to operate MongoDB. In general, all the functions in the MongoDB command line can be implemented, and the parameters formats are basically similar. The previous version of PHP7 and the later versions of PHP7 have different operations on MongoDB. This article mainly uses the previous version of PHP7 as an example to explain the various operations of PHP on MongoDB. Finally, let’s briefly explain the operations of PHP7 and later versions of MongoDB.

1. Data insertion

//insert()
//Article 1: an array or object// Parameter 2: Extended Options// fsync: Default is false. If true, mongo will force the data to the hard disk before confirming that the data is inserted successfully.// j: Default is false. If true, mongo will force the data to be written to the log before confirming that the data is inserted successfully.// w: The default is 1, the write operation will be confirmed by the (main) server. If it is 0, it will not be confirmed. When using the replication set, it is set to n to ensure that the main server successfully replicates the data modification to n nodes before confirming it.// wtimeout: default is 10000 (ms), used to specify the time when the server waits for the reception of acknowledgement// timeout: Specify the timeout (milliseconds) when the client needs to wait for the server to respond$mongo = new MongoClient('mongodb://localhost:27017');
$db = $mongo->mf;//Select a database$collection = $db->friend;//Select a document collection$doc = [//Define a document, that is, an array  'First Name' => 'Jet',
  'Last Name' => 'Wu',
  'Age' => 26,
  'Phone' => '110',
  'Address' => [
    'Country' => 'China',
    'City' => 'Shen Zhen'
  ],
  'E-Mail' => [
    '123456@',
    '666666@',
    '8888888@',
    '77887788@'
  ]
];
$res = $collection->insert($doc);//Insert a document into the collectionecho '<pre>';
print_r($res);//$res['ok']=1 means that the insertion is successful

2. Data query

1. Query a single document:

//findOne()
// Parameter 1: Search criteria// Parameter 2: Specify the return field, array('fieldname' => true, 'fieldname2' => true).  The _id field will always be returned unless '_id'=>false is explicitly added to the second parameter.  If not set, all fields will be returned$mongo = new MongoClient('mongodb://localhost:27017');
$db = $mongo->mf;
$collection = $db->friend;
$one = $collection->findOne(['First Name' => 'Jet']);
echo '<pre>';
print_r($one);//Return an array, if the data cannot be found, it will return NULL

2. Query multiple documents:

//find()
// Parameter 1: Search criteria// Parameter 2: Specify the return field, array('fieldname' => true, 'fieldname2' => true).  The _id field will always return unless explicitly set to false and does not return.  If not set, all fields will be returned$mongo = new MongoClient('mongodb://localhost:27017');
$db = $mongo->mf;
$collection = $db->friend;
$cursor = $collection->find(['' => 'China']);// Use dot operator to find array elementsecho '<pre>';
while($doc = $cursor->getNext()) {//Loop to read each matching document  print_r($doc);
}

Define the query using various conditional operators:

//mongodb uses $lt, $lte, $eq, $gte, $gt, $gt, $ne to represent <, <=, =, >=, >, <> respectively, for integer field query$mongo = new MongoClient('mongodb://localhost:27017');
$db = $mongo-&gt;mf;
$collection = $db-&gt;friend;
$cursor = $collection-&gt;find(['Age' =&gt; ['$gt' =&gt; 30]]);
echo '&lt;pre&gt;';
while($doc = $cursor-&gt;getNext()) {
  print_r($doc);
}
//Query all unduplicate values ​​of a field$res = $collection-&gt;distinct('Age');
//$in: Match any of multiple values$cursor = $collection-&gt;find(['' =&gt; ['$in' =&gt; ['China', 'USA']]]);
//$all: Match all values ​​in multiple values ​​(for array field query)$cursor = $collection-&gt;find(['E-Mail' =&gt; ['$all' =&gt; ['123456@', '77887788@']]]);
//$or: or query$cursor = $collection-&gt;find(['$or' =&gt; [['First Name' =&gt; 'Jet'], ['' =&gt; 'USA']]]);
//$slice: Get the specified number of elements in the array field, located in the second parameter of the find() function$cursor = $collection-&gt;find(['First Name' =&gt; 'Jet'], ['E-Mail' =&gt; ['$slice' =&gt; 2]]);//Return only the first two emails$cursor = $collection-&gt;find(['First Name' =&gt; 'Jet'], ['E-Mail' =&gt; ['$slice' =&gt; -2]]);//Return only the last two emails$cursor = $collection-&gt;find(['First Name' =&gt; 'Jet'], ['E-Mail' =&gt; ['$slice' =&gt; [1, 2]]]);//Ignore the first one and return to the next two//$exists: Query based on whether a field has set value or not.$cursor = $collection-&gt;find(['Hobby' =&gt; ['$exists' =&gt; false]]);// Find documents with no value set in the Hobby field//Regular expression query$cursor = $collection-&gt;find(['First Name' =&gt; new MongoRegex('/^Je/i')]);//Look for documents with the First Name field starting with Je, ignoring case differences

Use other functions provided by the MongoCursor class:

//Sorting: 1 ascending order, -1 descending order$cursor-&gt;sort(['Age' =&gt; 1]);
//Ignore the previous n matching documents$cursor-&gt;skip(1);
//Only return the first n matching documents (limit() and skip() can realize the data paging function)$cursor-&gt;limit(1);
//Total number of matching documents$cursor-&gt;count();
//Specify query index$cursor-&gt;hint(['Last Name' =&gt; -1]);//If the index does not exist, an error will be reported

Aggregation query: group data statistics

//Aggregation query: group data statistics$mongo = new MongoClient('mongodb://localhost:27017');
$db = $mongo-&gt;mf;
$collection = $db-&gt;friend;
$res = $collection-&gt;aggregate([
  '$group' =&gt; [
    '_id' =&gt; '$',//Group fields, please add "$". Here you are grouped according to the value of an element in the array field.    'total' =&gt; ['$sum' =&gt; 1],// Find the sum, which means that each matching document sum is added 1    'maxAge' =&gt; ['$max' =&gt; '$Age'],//The maximum value of the Age field in the group    'minAge' =&gt; ['$min' =&gt; '$Age']//The minimum value of Age field in the group  ]
]);
echo '&lt;pre&gt;';
print_r($res);//Return an array, $ret['result'] is an array, storing statistical results//There are aggregate queries for other operations: the order of execution between multiple operations depends on the order of their positions//All operations in the aggregate query, including '$group', are optional.$mongo = new MongoClient('mongodb://localhost:27017');
$db = $mongo-&gt;mf;
$collection = $db-&gt;friend;
$res = $collection-&gt;aggregate([
  [//Filtering conditions: Only aggregate the original documents that meet the conditions. If placed after '$group', only the result documents that meet the conditions are returned will be returned.    '$match' =&gt; ['Age' =&gt; ['$gt' =&gt; 30]]
  ],
  [//Specify grouping fields and statistics fields    '$group' =&gt; [
      '_id' =&gt; '$',
      'totalAge' =&gt; ['$sum' =&gt; '$Age']// Calculate the sum of each grouping Age field    ]
  ],
  //If the following operations are placed before '$group', they will act on the original document before aggregation. If placed after '$group', they will act on the result document after aggregation.  ['$unwind' =&gt; '$E-Mail'],//Split the document containing a certain array type field into multiple documents, and the value of the field with the same name of each document is one value in the array.  ['$project' =&gt; ['myAge' =&gt; '$Age', 'First Name' =&gt; '$First Name']],//Specify the return field, you can rename the field, format: return field name => $Original field name  ['$skip' =&gt; 2],//Skip the specified number of documents  ['$limit' =&gt; 2],//Return only the specified number of documents  ['$sort' =&gt; ['totalAge' =&gt; 1]]//Sort]);
echo '&lt;pre&gt;';
print_r($res);

3. Data modification

//update()
//Parameter 1: Update condition, specify the updated target object.// Parameter 2: Specify the object used to update the matching record.//Parameter 3: Extend option group.// upsert: If set to true, a new document will be created when there is no matching document.// multiple: Default is false. If set to true, all matching documents will be updated.// fsync: If set to true, the w parameter will be overwritten to 0, and the data will be synchronized to disk before the update result is returned.// w: The default is 1; if set to 0, the update operation will not be confirmed; when using the replication set, it can be set to n to ensure that the main server only confirms the update operation after replicating the modification to n nodes// j: Default is false. If set to true, the data will be written to the log before the update result is returned.// wtimeout: default is 10000 (ms), used to specify the time when the server waits for the reception of acknowledgement// timeout: Specify the timeout (milliseconds) when the client needs to wait for the server to respond//Note: If no modification operator is used, the matching document will be replaced directly with the object specified in parameter 2.//$inc: Add the value of a specific key. If the field does not exist, create a new field and assign a value.$mongo = new MongoClient('mongodb://localhost:27017');
$db = $mongo-&gt;mf;
$collection = $db-&gt;friend;
$res = $collection-&gt;update(['First Name' =&gt; 'Jet'], ['$inc' =&gt; ['Age' =&gt; 2]]);
echo '&lt;pre&gt;';
print_r($res);//$res['ok']=1 means the modification is successful, $res['nModified'] means the number of modified documents//$set: Reset the value of a specific key. If the field does not exist, create a new field and assign a value.$res = $collection-&gt;update(['First Name' =&gt; 'Jet'], ['$set' =&gt; ['Hobby' =&gt; 'pingpong']]);
//$unset: delete the field$res = $collection-&gt;update(['First Name' =&gt; 'Jet'], ['$unset' =&gt; ['Hobby' =&gt; 1]]);
//$rename: Rename the field. If the field does not exist, no operation will be performed.$res = $collection-&gt;update(['First Name' =&gt; 'Jet'], ['$rename' =&gt; ['Hobby' =&gt; 'hobby', 'Age' =&gt; 'age']]);
//Note: If the field with the specified name has been used in the document, the field will be deleted and then renamed.//$setOnInsert: When upsert is set to true, and when an insert operation occurs, set a certain field to a specific$res = $collection-&gt;update(['First Name' =&gt; 'jet'], ['$setOnInsert' =&gt; ['lang' =&gt; 'English']], ['upsert' =&gt; true]);
//$push: Add a value to the specified field (acted on the array field). If the field does not exist, the field will be created first. If the field value is not an array, an error will be reported.$res = $collection-&gt;update(['First Name' =&gt; 'Jet'], ['$push' =&gt; ['E-Mail' =&gt; '123123@']]);
//$push: Add multiple values ​​to the specified field (acting on the array field). If the field does not exist, the field will be created first. If the field value is not an array, an error will be reported.$res = $collection-&gt;update(['First Name' =&gt; 'Jet'], ['$pushAll' =&gt; ['E-Mail' =&gt; ['666@', '8888888@']]]);
//Use $push and $each to add multiple values ​​to a field (acting on the array field). If the field does not exist, the field will be created first. If the field value is not an array, an error will be reported.$res = $collection-&gt;update(['First Name' =&gt; 'Jet'], ['$push' =&gt; ['E-Mail' =&gt; ['$each' =&gt; ['123123@', '666@']]]]);
//$addToSet: Add data to the array (only add data to the array if the target array does not have this data)$res = $collection-&gt;update(['First Name' =&gt; 'Jet'], ['$addToSet' =&gt; ['E-Mail' =&gt; '123123@']]);
$res = $collection-&gt;update(['First Name' =&gt; 'Jet'], ['$addToSet' =&gt; ['E-Mail' =&gt; ['$each' =&gt; ['123123@', '666@']]]]);
//$pop: Delete an element from the array, -1 means delete the first element, 1 means delete the last element (in fact, both negative numbers delete the first element, and 0 or positive numbers delete the last element)$res = $collection-&gt;update(['First Name' =&gt; 'Jet'], ['$pop' =&gt; ['E-Mail' =&gt; 1]]);
//$pull: Delete all specified values ​​in the array$res = $collection-&gt;update(['First Name' =&gt; 'Jet'], ['$pull' =&gt; ['E-Mail' =&gt; '123123@']]);
//$pullAll: Delete all values ​​of multiple elements in the array$res = $collection-&gt;update(['First Name' =&gt; 'Jet'], ['$pullAll' =&gt; ['E-Mail' =&gt; ['123123@', '666@']]]);
//save()
// Parameter 1: The information array you want to save// Parameter 2: Extended Options// fsync: If set to true, the w parameter will be overwritten to 0, and the data will be synchronized to disk before the update result is returned.// w: The default is 1; if set to 0, the update operation will not be confirmed; when using the replication set, it can be set to n to ensure that the main server only confirms the update operation after replicating the modification to n nodes// j: Default is false. If set to true, the data will be written to the log before the update result is returned.// wtimeout: default is 10000 (ms), used to specify the time when the server waits for the reception of acknowledgement// timeout: Specify the timeout (milliseconds) when the client needs to wait for the server to respond//Note: If it already exists, update it, and if it does not exist, insert it; use the information array specified in parameter 1 to replace the entire document.//If you want to update, you should specify the value of the _id key in parameter 1.$mongo = new MongoClient('mongodb://localhost:27017');
$db = $mongo-&gt;mf;
$collection = $db-&gt;friend;
$doc = [//Define a document, that is, an array  'First Name' =&gt; 'Jet',
  'Last Name' =&gt; 'Wu',
  'Age' =&gt; 26,
  'Phone' =&gt; '110',
  'Address' =&gt; [
    'Country' =&gt; 'China',
    'City' =&gt; 'Shen Zhen'
  ],
  'E-Mail' =&gt; [
    '123456@',
    '666666@',
    '8888888@',
    '77887788@'
  ]
];
$res = $collection-&gt;save($doc);
echo '&lt;pre&gt;';
print_r($res);//$res['ok']=1 means the operation is successful, $res['updatedExisting']=1 means update, $res['upserted']=1 means insertion//findAndModify()
// Parameter 1: Specify query conditions// Parameter 2: Specify the information used to update the document// Parameter 3: Optional, specify the field you want to return// Parameter 4: Extended Options// sort: sort matching documents in a specific order// remove: If set to true, the first matching document will be deleted// update: If set to true, update operation will be performed on the selected document// new: Default is false. If set to true, the updated document will be returned, otherwise the updated document will be returned.// upsert: If set to true, a new document will be inserted when no matching document is found$mongo = new MongoClient('mongodb://localhost:27017');
$db = $mongo-&gt;mf;
$collection = $db-&gt;friend;
$res = $collection-&gt;findAndModify(['First Name' =&gt; 'Jet'], ['$push' =&gt; ['E-Mail' =&gt; '111@']]);
echo '&lt;pre&gt;';
print_r($res);

4. Data deletion

//remove()
//Parameter 1: Query conditions// Parameter 2: Extended Options// justOne: If set to true, at most only one matching document will be deleted// fsync: If set to true, the w parameter will be overwritten to 0, and the data will be synchronized to disk before the update result is returned.// w: The default is 1; if set to 0, the update operation will not be confirmed; when using the replication set, it can be set to n to ensure that the main server only confirms the update operation after replicating the modification to n nodes// j: Default is false. If set to true, the data will be written to the log before the update result is returned.// wtimeout: default is 10000 (ms), used to specify the time when the server waits for the reception of acknowledgement// timeout: Specify the timeout (milliseconds) when the client needs to wait for the server to respond$mongo = new MongoClient('mongodb://localhost:27017');
$db = $mongo-&gt;mf;
$collection = $db-&gt;friend;
$res = $collection-&gt;remove(['First Name' =&gt; 'jet']);
echo '&lt;pre&gt;';
print_r($res);//$res['n'] means that several documents have been deleted

The above is the MongoDB operation of previous versions of PHP7. The following is a brief introduction to the operations of later versions of PHP7.

How to operate PHP7

Data Insertion:

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$bulk = new MongoDB\Driver\BulkWrite;
$bulk-&gt;insert(['name' =&gt; 'JetWu5', 'age' =&gt; 26]);
$bulk-&gt;insert(['name' =&gt; 'JetWu6', 'age' =&gt; 26]);
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);//Optional, modify and confirm$res = $manager-&gt;executeBulkWrite('', $bulk, $writeConcern);
echo '&lt;pre&gt;';
print_r($res);

Data query:

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$query = new MongoDB\Driver\Query(['age' => 24], ['sort' => ['age' => 1]]);
$cursor = $manager->executeQuery('', $query);
$data = [];
foreach($cursor as $doc) {
  $data[] = $doc;
}
echo '<pre>';
print_r($data);

Data modification:

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$bulk = new MongoDB\Driver\BulkWrite;
$bulk-&gt;update(
  ['name' =&gt; 'JetWu5'],
  ['$set' =&gt; ['age' =&gt; 30, 'promise' =&gt; 'always smile!']]
);
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);//Optional, modify and confirm$res = $manager-&gt;executeBulkWrite('', $bulk, $writeConcern);
echo '&lt;pre&gt;';
print_r($res);

Data deletion:

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$bulk = new MongoDB\Driver\BulkWrite;
$bulk-&gt;delete(['name' =&gt; 'JetWu3']);
$bulk-&gt;delete(['name' =&gt; 'JetWu4']);
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);//Optional, modify and confirm$res = $manager-&gt;executeBulkWrite('', $bulk, $writeConcern);
echo '&lt;pre&gt;';
print_r($res);

For more information about PHP related content, please check out the topic of this site:Complete collection of PHP+MongoDB database operation skills》、《Summary of PHP's skills to operate database based on pdo》、《PHP object-oriented programming tutorial》、《Summary of usage of php strings》、《PHP+mysql database operation tutorial"and"Summary of common database operation techniques for php

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