PHP operation MongoDB Implementation and deletion of the function

Source: Internet
Author: User
Tags findone mongoclient
This article mainly introduces the PHP operation MongoDB implementation of adding and removing functions, combined with examples of the form of a summary of the PHP operation MongoDB Common skills, and with PHP7 operation MongoDB method, with a certain reference value, the need for friends can refer to the next

The example of this article describes the PHP operation MongoDB implementation and deletion of the function. Share to everyone for your reference, as follows:

MongoDB's PHP driver provides some core classes to manipulate MongoDB, in general, the functionality of the MongoDB command line, it can be implemented, and the format of the parameters are basically similar. PHP7 Previous version and PHP7 version of the operation of the MongoDB is different, this article mainly in the previous version of PHP7 to explain the various PHP operation of MongoDB, and finally briefly explain the PHP7 later version of the operation of MongoDB.

First, data insertion


Insert ()///Parameter 1: An array or an object//Parameter 2: Extended Options//Fsync: Default is False, if true MONGO will force data to be written to the hard drive before confirming the data is inserted successfully//J: Default is False, If true, MONGO will force the data to be written to the Log//w: Default is 1, the write operation will be confirmed by the (primary) server, if 0 will not be confirmed, the use of the replica set to n is used to ensure that the master server will successfully replicate data modification to n nodes and then confirm// Wtimeout: The default is 10000 (milliseconds), which specifies the time the server waits to receive an acknowledgement/timeout: Specifies the time-out (in milliseconds) that the client needs to wait for the server response $mongo = new Mongoclient (' mongodb:// localhost:27017 '); $db = $mongo->mf;//Select a database $collection = $db->friend;//Select a document collection $doc = [//define a document, an array  ' first Name ' = ' + ' Jet ',  ' last Name ' = ' Wu ', ' age ' = ' + ', ' Phone ' ' + '  , '  Address ' = [    ' Co Untry ' + ' China ',    ' city ' = ' Shen zhen '  ],  ' e-mail ' and ' = '    123456@qq.com ',    ' 666666@ Sina.com ',    ' 8888888@qq.com ',    ' 77887788@qq.com '  ]; $res = $collection->insert ($doc);// Insert a document into the collection echo ' <pre> ';p rint_r ($res);//$res [' OK ']=1 indicates successful insertion


Second, data query

1. Query a single document:


FindOne ()//Parameter 1: Search condition//Parameter 2: Specify return field, Array (' fieldname ' = = True, ' fieldname2 ' = true). The _id field will always return unless the ' _id ' =>false is explicitly added to the second parameter. Do not set returns all fields $mongo = new Mongoclient (' mongodb://localhost:27017 '); $db = $mongo->mf; $collection = $db->friend; $one = $collection->findone ([' First Name '] + ' Jet '), Echo ' <pre> ';p rint_r ($one);//Returns an array, and returns NULL if no data is found


2. Querying Multiple documents:


Find ()//Parameter 1: Search condition//Parameter 2: Specify the Return field, Array (' fieldname ' = = True, ' fieldname2 ' = true). The _id field is always returned unless it is explicitly set to False. Do not set to return all fields $mongo = new Mongoclient (' mongodb://localhost:27017 '); $db = $mongo->mf; $collection = $db->friend;$ cursor = $collection->find ([' address.country ' = ' China ']);//Use the dot operator to find the array element echo ' <pre> '; while ($doc = $ Cursor->getnext ()) {//loop read each matching document  Print_r ($doc);}


Use various conditional operators to define the query:


MongoDB uses $lt, $lte, $eq, $gte, $GT, $ne to represent <, <=, =, >=, >, <&gt, for integer field queries $mongo = new Mongoclient (' mongodb://localhost:27017 '); $db = $mongo->mf; $collection = $db->friend; $cursor = $collection->find ([' Age ' = > [' $gt ' = +]]; Echo ' <pre> '; while ($doc = $cursor->getnext ()) {Print_r ($doc);} Query for all the distinct values of a field $res = $collection->distinct (' age '),//$in: Matches any one of several values $cursor = $collection->find ([' Address.country ' = [' $in ' = [' China ', ' USA ']]);//$all: Matches all values in multiple values (for array field queries) $cursor = $collection->find ([' e-mail ' = = [' $all ' = [' 123456@qq.com ', ' 77887788@qq.com ']]);//$or: or query $cursor = $collection->find ([' $or ' = > [' first Name ' = ' Jet '], [' address.country ' + ' USA ']]);//$slice: Gets the specified number of elements in the array field, in the second argument of the Find () function $cursor = $collection->find ([' first Name ' = ' Jet '], [' e-mail ' = [' $slice ' + 2]]);//returns only the top two email$cursor = $ Collection->find ([' first Name ' = ' Jet '], [' e-mail ' = [' $slice ' +-2]]);//Return only the last two email$cursor = $colleCtion->find ([' first Name ' = ' Jet '], [' e-mail ' = [' $slice ' = [1, 2]]]);//Ignore the number one and return to the next two//$ Exists: query based on whether a field has a set value $cursor = $collection->find ([' Hobby ' = ' = ' $exists ' = ' = false]]);//Find the Hobby field not set the value of the document// The regular expression query $cursor = $collection->find ([' First name ' = ' = new Mongoregex ('/^je/i ')]);//Find documents with the first Name field beginning with Je, ignoring case differences


Use the other functions provided by the Mongocursor class:


Sort: 1 Ascending,-1 descending $cursor->sort ([' Age ' = 1]);//ignores the first n matching documents $CURSOR->SKIP (1);//returns only the first n matching documents (limit () and Skip () The data paging function can be used together) $cursor->limit (1);//The total number of matching documents $cursor->count ();//Specify Query index $cursor->hint ([' last Name ' = 1]) //If the index does not exist, it will be an error


Aggregate query: group statistics on data


Aggregate query: Group statistics on data $mongo = new Mongoclient (' mongodb://localhost:27017 '); $db = $mongo->mf; $collection = $db Friend; $res = $collection->aggregate ([' $group ' = [' _id ' and ' = ' $Address. Country ',///Group field, note to add "$", here is a tuple based on the array field The vegetarian values are grouped by ' total ' and [' $sum ' and ' 1],//' Sum, which represents the sum of each matching document plus 1 ' maxAge ' + = [' $max ' = ' = ' $Age '],//the Age field Max ' mi NAge ' = = [' $min ' + ' $Age ' age field minimum in]//Group]]); Echo ' <pre> ';p rint_r ($res);//returns an array $ret [' result '] Aggregated queries that hold statistical results//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->mf; $collection = $db->friend; $res = $ Collection->aggregate ([[//filter: Only the original document that meets the criteria is aggregated, and if it is placed after ' $group ', only the result document that matches the condition is returned ' $match ' = = [' Age ' = [' $gt ' + 30]], [//Specify the Grouping field, the statistic field ' $group ' + = [' _id ' + ' $Address. Country ', ' totalage ' and ' = ' $sum ' =&gt ; ' $Age ']//calculates the sum of the age fields of each grouping]],//The following operations are used for the original document before aggregation, if placed before the ' $group ', and after the ' $group ' is aggregated for the result document [' $UNWInd ' + ' $E-mail '],//splits a document that contains a field of an array type into multiple documents, and the value of the field with the same name for each document is a value in the array. [' $project ' = [' myAge ' + ' $Age ', ' first Name ' + ' $First name ']],//Specify the return field, you can rename the field, Format: return field name = = $ original field name [' $ Skip ' = + 2],//skips a specified number of documents [' $limit ' + = 2],//returns only the specified number of documents [' $sort ' = = [' totalage ' + 1]]//sort]; Echo ' <pre> ' ;p Rint_r ($res);


Third, data modification


Update ()//Parameter 1: Update the condition to specify the target object for the update. Parameter 2: Specifies the object that is used to update the matching record. Parameter 3: Extended option group. Upsert: If set to true, a new document is created when there is no matching document. Multiple: The default is False, and if set to true, the matching document will all be updated. Fsync: If the set to true,w parameter is overwritten with 0, the data will be synchronized to disk before the update results are returned. W: Default is 1, if set to 0, the update operation will not be confirmed, the copy set can be set to n, to ensure that the primary server after the modification to n nodes to confirm the update operation//J: Default is False, if set to true, the data will be written to the log before the update results are returned. Wtimeout: Default is 10000 (milliseconds) to specify the time that the server waits to receive an acknowledgement/timeout: Specifies the time-out (in milliseconds) that the client needs to wait for the server to respond: If you do not use any modification operators, The matching document will be replaced directly with the object specified by parameter 2. $inc: Increase the value of a specific key, create a new field if the field does not exist, and assign a value $mongo = new Mongoclient (' mongodb://localhost:27017 '); $db = $mongo->mf; $collection = $db->friend; $res = $collection->update ([' first Name ' = ' Jet '], [' $inc ' = [' age ' = 2]]); Echo ' <pre&gt ;'; Print_r ($res);//$res [' OK ']=1 indicates a successful modification, $res [' nmodified '] indicates the number of modified documents//$SET: Resets the value of a particular key, creates a new field and assigns a value if the field does not exist $res = $collection- >update ([' first Name ' = ' Jet '], [' $set ' = = [' Hobby ' = ' pingpong ']]);//$unset: Delete field $res = $collection Update ([' first Name ' = ' Jet '], [' $unset ' = [' Hobby ' + 1]]),//$rename: Renames the field and does nothing if the field does not exist $res = $collection- &Gt;update ([' first Name ' = ' Jet '], [' $rename ' = [' Hobby ' = ' Hobby ', ' age ' + ' age ']);//NOTE: If a word with the specified name is already in the document Segment, the field will be deleted and then renamed. $setOnInsert: When Upsert is set to true and an insert operation occurs, a field is set to a specific $res = $collection->update ([' first Name ' = ' "Jet '], [' $ Setoninsert ' = = [' lang ' = ' English '], [' upsert ' = true]);//$push: Adds a value to the specified field (acting on the array field), and if the field does not exist, the field is created first. If the field value is not an array will error $res = $collection->update ([' first Name ' = ' Jet '], [' $push ' = = [' e-mail ' = ' 123123@qq.com ']]); /$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 error $res = $collection->update ([' first Name ' = ' Jet '], [' $ Pushall ' = = [' e-mail '] = [' 666@qq.com ', ' 8888888@qq.com ']]);//Use $push and $each to add multiple values to a field (acting on an array field) and create a field if the field does not exist. If the field value is not an array will error $res = $collection->update ([' first Name ' = ' Jet '], [' $push ' = = [' e-mail '] and [' $each ' = = [' 12312 3@qq.com ', ' 666@qq.com ']]);//$addToSet: Adds data to the array (only adds data to the array when the destination array does not have that data) $res = $collection->update ([' First Name ' + ' Jet '], [' $addToSet ' = = [' E-mail ' = ' 123123@qq.com ']); $res = $collection->update ([' first Name ' = ' Jet '], [' $addToSet ' = = [' e-mail '] = [' $ Each ' = ' [' 123123@qq.com ', ' 666@qq.com ']]);//$pop: Removes an element from an array, 1 means the first element is deleted, and 1 means that the last element is deleted (negative numbers actually delete the first element, 0 or positive to delete the last element) $res = $collection->update ([' first Name ' = ' Jet '], [' $pop ' = = [' e-mail ' + 1]]);//$ Pull: Deletes all specified values in the array $res = $collection->update ([' first Name ' = ' Jet '], [' $pull ' = = [' e-mail ' = ' 123123@qq.com '] ]);//$PULLALL: Removes all values for multiple elements in the array $res = $collection->update ([' first Name ' = ' Jet '], [' $pullAll ' = = [' e-mail '] [ ' 123123@qq.com ', ' 666@qq.com ']]);//save ()//Parameter 1: Array of information you wish to save//Parameter 2: Extended option//Fsync: If set to true,w parameter will be overwritten with 0, data will be synchronized to disk before update results are returned. W: Default is 1, if set to 0, the update operation will not be confirmed, the copy set can be set to n, to ensure that the primary server after the modification to n nodes to confirm the update operation//J: Default is False, if set to true, the data will be written to the log before the update results are returned. Wtimeout: Default is 10000 (milliseconds) to specify the time that the server waits to receive an acknowledgement/timeout: Specifies the time-out (in milliseconds) that the client needs to wait for the server response: Update if it exists, insert if it does not exist Replace the entire document with an array of information specified by parameter 1 when updating. 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->mf; $collection = $db->friend; $doc = [//define a document, i.e. an array ' first name ' = ' Jet ', ' last name ' + ' Wu ', ' age ' = >, ' Phone ' = ' + ', ' Address ' = [' country ' = ' China ', ' city ' = ' Shen zhen '], ' e-mail ' =& Gt [' 123456@qq.com ', ' 666666@sina.com ', ' 8888888@qq.com ', ' 77887788@qq.com ']; $res = $collection->save ($doc), echo ' <pre> ';p rint_r ($res),//$res [' OK ']=1 indicates successful operation, $res [' updatedexisting ']= 1 means update, $res [' upserted ']=1 means insert//findandmodify ()//Parameter 1: Specify query Condition//Parameter 2: Specify information to update the document//Parameter 3: Optional, specify the field you want to return//Parameter 4: Extended Options// Sort: Sorting a matching document in a specific order/remove: If set to true, the first matching document will be deleted//update: If set to true, the update operation will be performed on the selected document//NEW: false By default, Returns the updated document if set to True, otherwise returns the pre-update document//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->mf; $collection = $db->friend; $res = $collection->findandmodify ([' first Name ' = = ') Jet '], [' $push ' = [' e-mail ' = ' 111@qq.com ']]; Echo ' <pre> ';p rint_r ($res);


Iv. Data Deletion


Remove ()//Parameter 1: Query condition//Parameter 2: Extended option//Justone: If set to true, only one matching document will be deleted//Fsync: If set to true,w parameter will be overwritten with 0, data will be synchronized to disk before update results are returned. W: Default is 1, if set to 0, the update operation will not be confirmed, the copy set can be set to n, to ensure that the primary server after the modification to n nodes to confirm the update operation//J: Default is False, if set to true, the data will be written to the log before the update results are returned. Wtimeout: The default is 10000 (milliseconds), which specifies the time the server waits to receive an acknowledgement/timeout: Specifies the time-out (in milliseconds) that the client needs to wait for the server response $mongo = new Mongoclient (' mongodb:// localhost:27017 '); $db = $mongo->mf; $collection = $db->friend; $res = $collection->remove ([' first Name ' = = ') Jet ']), echo ' <pre> ';p rint_r ($res);//$res [' n '] means that several documents have been deleted


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

PHP7 Method of operation

Data insertion:


$manager = new Mongodb\driver\manager (' mongodb://localhost:27017 '); $bulk = new Mongodb\driver\bulkwrite; $bulk  Insert ([' name ' = ' JetWu5 ', ' age ' = +]); $bulk->insert ([' name ' = ' JetWu6 ', ' age ' =]); $writeConcern = New Mongodb\driver\writeconcern (mongodb\driver\writeconcern::majority, 1000);//optional, modify confirmation $res = $manager Executebulkwrite (' Wjt.friend ', $bulk, $writeConcern), Echo ' <pre> ';p rint_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 (' Wjt.friend ', $query); $data = [];foreach ($cursor as $doc) {  $data [] = $doc;} Echo ' <pre> ';p rint_r ($data);


Data modification:


$manager = new Mongodb\driver\manager (' mongodb://localhost:27017 '); $bulk = new Mongodb\driver\bulkwrite; $bulk Update (  [' name ' = ' JetWu5 '],  [' $set ' = [' age ' = ', ' promise ' = ' always smile! ']]; $writeConcern = new Mongodb\driver\writeconcern (mongodb\driver\writeconcern::majority, 1000);//optional, modify confirm $res = $ Manager->executebulkwrite (' Wjt.friend ', $bulk, $writeConcern), Echo ' <pre> ';p rint_r ($res);


Data deletion:


$manager = new Mongodb\driver\manager (' mongodb://localhost:27017 '); $bulk = new Mongodb\driver\bulkwrite; $bulk Delete ([' name ' = ' JetWu3 ']); $bulk->delete ([' name ' = ' JetWu4 ']); $writeConcern = new Mongodb\driver\ Writeconcern (mongodb\driver\writeconcern::majority, 1000);//optional, modify confirmation $res = $manager->executebulkwrite (' Wjt.friend ', $bulk, $writeConcern), Echo ' <pre> ';p rint_r ($res);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.