In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how php modifies mongo". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how php modifies mongo".
Php methods to modify mongo data: 1, create a PHP sample file and connect to the mongodb database; 2, use conditional operators to define queries; 3, modify data through update and other methods.
This article operating environment: windows7 system, PHP7.1 version, DELL G3 computer
How does php modify mongo?
PHP operation MongoDB (add, delete, modify and check)
MongoDB's PHP driver provides some core classes to manipulate MongoDB. Generally speaking, it can implement all the functions on the MongoDB command line, and the format of the parameters is basically similar. The operation of MongoDB is different between the previous version of PHP7 and the version after PHP7. This article mainly takes the previous version of PHP7 as an example to explain the various operations of PHP to MongoDB, and finally briefly explains the operation of MongoDB in the future version of PHP7.
I. data insertion
/ / insert () / / Parameter 1: an array or object / / Parameter 2: extension option / / fsync: default is false, if true, mongo will force data to be written to the hard disk before confirming that the data is inserted successfully / / j: default is false, if it is true, mongo will force data to be written to the log / / w: default is 1, and the write operation will be confirmed by the (primary) server If 0, it will not be confirmed. Set to n when using replication set to ensure that the master server successfully replicates data modifications to n nodes before confirming / / wtimeout: default is 10000 (milliseconds), used to specify the time for the server to wait for confirmation / / timeout: specify the timeout time that the client needs to wait for the server response (milliseconds) $mongo = new MongoClient ('mongodb://localhost:27017') $db = $mongo- > mf;// Select Database $collection = $db- > friend / / Select a document collection $doc = [/ / define a document That is, an array of 'First Name' = >' Jet', 'Last Name' = >' Wu', 'Age' = > 26,' Phone' = > '110mm,' Address' = > ['Country' = >' China', 'City' = >' Shen Zhen'], 'Elyle Mail' = > [' 123456qq.compositions, '6666examples sina.compositions,' 888883q.compositions' '77887788q.com'] $res = $collection- > insert ($doc); / / insert a document echo''; print_r ($res) into the collection; / / $res ['ok'] = 1 indicates that the insert is successful
II. Data query
1. Query a single document:
/ / findOne () / / Parameter 1: search condition / / Parameter 2: specify the returned field, array ('fieldname' = > true,' fieldname2' = > true). The _ id field is always returned unless you explicitly add'_ id'= > false to the second parameter. If it is not set, all fields $mongo = new MongoClient ('mongodb://localhost:27017'); $db = $mongo- > mf;$collection = $db- > friend;$one = $collection- > findOne ([' First Name' = > 'Jet']); echo''; print_r ($one); / / an array is returned. If no data is found, NULL is returned.
two。 Query multiple documents:
/ / find () / / Parameter 1: search condition / / Parameter 2: specify the returned field, array ('fieldname' = > true,' fieldname2' = > true). The _ id field always returns unless it is explicitly set to false. If not set, all fields $mongo = new MongoClient ('mongodb://localhost:27017'); $db = $mongo- > mf;$collection = $db- > friend;$cursor = $collection- > find ([' Address.Country' = > 'China']) are returned; / / use the dot operator to find the array element echo'; while ($doc = $cursor- > getNext ()) {/ / cycle through each matching document print_r ($doc);}
Define the query using various conditional operators:
/ / mongodb uses $lt, $lte, $eq, $gte, $gt, $ne, respectively, to query $mongo = new MongoClient ('mongodb://localhost:27017') for integer fields; $db = $mongo- > mf;$collection = $db- > friend;$cursor = $collection- > find ([' Age' = > ['$gt' = > 30]]); echo''; while ($doc = $cursor- > getNext ()) {print_r ($doc) } / / query all non-repeating values of a field $res = $collection- > distinct ('Age'); / / $in: match any of the multiple values $cursor = $collection- > find ([' Address.Country' = > ['$in' = > ['China',' USA']) / / $all: matches all of the values in multiple values (for array field queries) $cursor = $collection- > find (['all'' = > ['$all' = > ['123456 values qq.compositions,' 77887788 values qq.compositions]); / / $or: or query $cursor = $collection- > find (['$or' = > [['First Name' = >' Jet'], ['Address.Country' = >' USA'])) / / $slice: get the specified number of elements in the array field, located in the second parameter of the find () function, $cursor = $collection- > find (['First Name' = >' Jet'], ['slice' Mail` = > [' $slice' = > 2]]); / / only the first two elements are returned as email$cursor = $collection- > find (['First Name' = >' Jet'], ['EmurMail' = > [' $slice' = >-2]]) / only return the last two email$cursor = $collection- > find (['First Name' = >' Jet'], ['EmurMail` = > [' $slice' = > [1, 2]); / / ignore the first and return the next two / / $exists: query $cursor = $collection- > find (['Hobby' = > [' $exists' = > false]] based on whether a field has a set value) / / find documents where the Hobby field is not set / / regular expression query $cursor = $collection- > find (['First Name' = > new MongoRegex (' / ^ Je/i')]); / / find documents where the First Name field begins with Je, ignoring case differences
Use other functions provided by the MongoCursor class:
/ sort: 1 Ascending,-1 descending $cursor- > sort (['Age' = > 1]); / / ignore the first n matching documents $cursor- > skip (1); / / return only the first n matching documents (limit () combined with skip () to achieve data paging) $cursor- > limit (1); / / Total number of matching documents $cursor- > count (); / / specify query index $cursor- > hint ([' Last Name' = >-1]) / / an error will be reported if the index does not exist
Aggregate query: group statistics of data
/ / aggregate query: group data statistics $mongo = new MongoClient ('mongodb://localhost:27017'); $db = $mongo- > mf;$collection = $db- > friend $res = $collection- > aggregate (['$group' = > ['_ id' = >'$Address.Country',// grouping field, please add "$". Here, grouping according to the value of an element in the array field 'total' = > [' $sum' = > 1], / / summing Indicates that the sum of each matching document is added with 1 'maxAge' = > [' $max' = >'$Age'], / / the maximum value of the Age field in the group 'minAge' = > [' $min' = >'$Age'] / / the minimum value of the Age field in the group])) Echo'; print_r ($res); / / returns an array. $ret ['result'] is an array that holds statistical results / / aggregate queries with other operations: the order in which multiple operations are executed depends on the order of their locations / / 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 criteria: aggregate only the original documents that meet the criteria If placed after'$group', only eligible result documents are returned'$match' = > ['Age' = > [' $gt' = > 30]], [/ / specify grouped fields, statistical fields'$group' = > ['_ id' = >'$Address.Country', 'totalAge' = > [' $sum' = >'$Age'] / / calculate the sum of grouped Age fields]] / / the following actions, if placed before'$group', act on the original document before aggregation If you put it after'$group', it acts on the result document ['$unwind' = >'$Emurmail'] after aggregation, / / splits the document containing a certain array type field into multiple documents, and the value of each document with the same name field is a value in the array. ['$project' = > ['myAge' = >' $Age', 'First Name' = >' $First Name']], / / specify the returned field, which can be renamed. Format: return field name = > $original field name ['$skip' = > 2], / / skip the specified number of documents ['$limit' = > 2], / / return only the specified number of documents ['$sort' = > ['totalAge' = > 1] / sort]); echo'' Print_r ($res)
III. Data modification
/ / update () / / Parameter 1: update condition and specify the target object for the update. / / Parameter 2: specifies the object used to update the matching record. / / Parameter 3: expand the 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 the true,w parameter is set to 0, the data will be synchronized to disk before the update result is returned. / / w: default is 1; if set to 0, the update operation will not be confirmed; when using replication set, it can be set to n to ensure that the master server confirms the update operation only after replicating the modification to n nodes. / j: default is false. If set to true, data will be written to the log before the update result is returned. / / wtimeout: default is 10000 (milliseconds), which is used to specify the time for the server to wait for confirmation / / timeout: specify the timeout time for the client to wait for the server response (milliseconds) / / Note: if no modification operator is used, the matching document will be directly replaced with the object specified in parameter 2. / / $inc: increase the value of a specific key. If the field does not exist, create a new field and assign the value $mongo = new MongoClient ('mongodb://localhost:27017'); $db = $mongo- > mf;$collection = $db- > friend;$res = $collection- > update ([' First Name' = > 'Jet'], [' $inc' = > ['Age' = > 2]]); echo'; print_r ($res) / / $res ['ok'] = 1 indicates successful modification, and $res [' nModified'] indicates 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 of $res = $collection- > update (['First Name' = >' Jet'], ['$set' = > ['Hobby' = >' pingpong']]) / / $unset: delete the field $res = $collection- > update (['First Name' = >' Jet'], ['$unset' = > ['Hobby' = > 1]]); / / $rename: rename the field and do nothing if the field does not exist $res = $collection- > update ([' First Name' = > 'Jet'], [' $rename' = > ['Hobby' = >' hobby', 'Age' = >' age']]) / / Note: if a field with the specified name is already used in the document, the field will be deleted and then renamed. / / $setOnInsert: when upsert is set to true and an insert operation occurs, set a field to a specific $res = $collection- > update (['First Name' = >' jet'], ['$setOnInsert' = > ['lang' = >' English']], ['upsert' = > true]) / / $push: add a value 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, it will report an error $res = $collection- > update (['First Name' = >' Jet'], ['$push' = > ['EmurMail' = >' 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, it will report an error $res = $collection- > update (['First Name' = >' Jet'], ['$pushAll' = > ['Emurq.compose,' 88888roomqq.com']])) / use $push and $each to add multiple values to a field (acting on an array field). If the field does not exist, the field will be created first. If the field value is not an array, it will report an error of $res = $collection- > update (['First Name' = >' Jet'], ['$push' = > [EmurMail` = > ['$each' = > ['123123 roomqq.compositions,' 666roomqq.compositions])) / / $addToSet: add data to the array (add data to the array only if the target array does not have it) $res = $collection- > update (['First Name' = >' Jet'], ['$addToSet' = > ['Elam Mail' = >' 123123 roomqq.com']]) $res = $collection- > update (['First Name' = >' Jet'], ['$addToSet' = > ['Emurmai' = > ['$each' = > ['123123 qq.compose,' 666roomqq.com'])) / / $pop: delete an element from the array,-1 means to delete the first element, 1 means to delete the last element (in fact, negative numbers delete the first element, 0 or positive numbers delete the last element) $res = $collection- > update (['First Name' = >' Jet'], ['$pop' = > ['EmurMail' = > 1]]) / / $pull: delete all specified values in the array $res = $collection- > update (['First Name' = >' Jet'], ['$pull' = > ['Elymel' = > '123123 roomqq.com']]); / / $pullAll: delete all values of multiple elements in the array $res = $collection- > update ([' First Name' = > 'Jet'], [' $pullAll' = > ['Eslink Mail' = > [' 123123roomqq.compose, '666roomqq.com']])) / / save () / / Parameter 1: information array to be saved / / Parameter 2: extension option / / fsync: if set to true,w parameter, the data will be overwritten to 0, and the data will be synchronized to disk before the update result is returned. / / w: default is 1; if set to 0, the update operation will not be confirmed; when using replication set, it can be set to n to ensure that the master server confirms the update operation only after replicating the modification to n nodes. / j: default is false. If set to true, data will be written to the log before the update result is returned. / / wtimeout: default is 10000 (milliseconds), which is used to specify the time for the server to wait for confirmation / / timeout: specify the timeout time for the client to wait for the server response (milliseconds) / / Note: update if it already exists, insert if it does not exist; replace the entire document with the information array specified in parameter 1. / / 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 That is, an array of 'First Name' = >' Jet', 'Last Name' = >' Wu', 'Age' = > 26,' Phone' = > '110mm,' Address' = > ['Country' = >' China', 'City' = >' Shen Zhen'], 'Elyle Mail' = > [' 123456qq.compositions, '6666examples sina.compositions,' 888883q.compositions' '77887788q.com'] $res = $collection- > save ($doc); echo''; print_r ($res) / / $res ['ok'] = 1 indicates successful operation, $res [' updatedExisting'] = 1 indicates update, $res ['upserted'] = 1 indicates insert / / findAndModify () / / parameter 1: specify query condition / / parameter 2: specify information / / parameter 3: optional, specify fields to be returned / / parameter 4: extension option / / 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, the update operation will be performed on the selected document / / new: default to false, if set to true, the updated document will be returned, otherwise the document before the update will be returned / / upsert: if set to true, a new document $mongo = new MongoClient ('mongodb://localhost:27017') will be inserted when no matching document is found $db = $mongo- > mf;$collection = $db- > friend;$res = $collection- > findAndModify (['First Name' = >' Jet'], ['$push' = > ['Emurmai' = > '111qq.com]]); echo'; print_r ($res)
IV. Data deletion
/ / remove () / / Parameter 1: query condition / / Parameter 2: expansion option / / justOne: if set to true, at most one matching document will be deleted / / fsync: if set to true,w parameter will be overwritten to 0, data will be synchronized to disk before the update result is returned. / / w: default is 1; if set to 0, the update operation will not be confirmed; when using replication set, it can be set to n to ensure that the master server confirms the update operation only after replicating the modification to n nodes. / j: default is false. If set to true, data will be written to the log before the update result is returned. / / wtimeout: default is 10000 (milliseconds), used to specify the time the server waits for acknowledgments / / timeout: specify the timeout time that the client needs to wait for the server response (milliseconds) $mongo = new MongoClient ('mongodb://localhost:27017'); $db = $mongo- > mf;$collection = $db- > friend;$res = $collection- > remove ([' First Name' = > 'jet']); echo''; print_r ($res); / / $res ['n'] indicates that several documents have been deleted
The above are the MongoDB operations of previous versions of PHP7. Here is a brief introduction to the operations of future versions of PHP7.
-PHP7 separator
Data insertion:
$manager = new MongoDB\ Driver\ Manager ('mongodb://localhost:27017'); $bulk = new MongoDB\ Driver\ BulkWrite;$bulk- > insert ([' name' = > 'JetWu5',' age' = > 26]); $bulk- > insert (['name' = >' JetWu6', 'age' = > 26]); $writeConcern = new MongoDB\ Driver\ WriteConcern (MongoDB\ Driver\ WriteConcern::MAJORITY, 1000); / optional, modify to confirm $res = $manager- > executeBulkWrite (' wjt.friend', $bulk, $writeConcern); echo'; 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 ('wjt.friend', $query); $data = []; foreach ($cursor as $doc) {$data [] = $doc;} echo'; print_r ($data)
Data modification:
$manager = new MongoDB\ Driver\ Manager ('mongodb://localhost:27017'); $bulk = new MongoDB\ Driver\ BulkWrite;$bulk- > update ([' name' = > 'JetWu5'], [' $set' = > ['age' = > 30,' promise' = > 'always examples']); $writeConcern = new MongoDB\ Driver\ WriteConcern (MongoDB\ Driver\ WriteConcern::MAJORITY, 1000); / / optional, modify to confirm $res = $manager- > executeBulkWrite ('wjt.friend', $bulk, $writeConcern); echo''; print_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 to confirm $res = $manager- > executeBulkWrite (' wjt.friend', $bulk, $writeConcern); echo'; print_r ($res) At this point, I believe you have a deeper understanding of "how php modifies mongo". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.