1. Connection
The default MongoDB port is 27017. Therefore, we can connect to MongoDB: $ MongoDB = new Mongo ('localhost') or specify the IP address and port $ MongoDB = new Mongo ('192. 168.127.1: 27017 ') the port can be changed.
If MongoDB enables authentication, that is, -- auth, the connection is: $ MongoDB = new Mongo ('root: w888168 @ localhost: 100 ');
2. Select a database
$ Db = $ MongoDB-> selectdbs ('dbname'); or you can directly specify the Database Name (because MongoDB can directly create a database that does not exist): $ db = $ MongoDB-> dbname;
3. Select collection)
$ Tables = $ db-> selectcolletion ('tablename') or $ tables = $ db-> tablename;
Next, you can operate the set.
4. Insert a new document)
Insert data into collection, such as personal information
$ One = array (
'Name' => 'lily ';
'Age' => 0,
'Hobby' => array (
'Dance ',
'Swim ',
'Music'
),
);
$ Res = $ tables-> insert ($ one, true );
The second parameter is used to wait for MongoDB to complete the operation to determine whether the operation is successful. The default value is false. this parameter is useful when a large number of records are inserted. After a new document is inserted, MongoDB will
Returns a record ID.
The result is: 1, indicating that the data has been inserted.
5. delete a document
It is relatively simple to delete a document: $ res = $ tables-> remove (Array ('name' => 'lily '));
Note: All eligible documents will be deleted here. If you only need to delete the first document that meets the conditions, add the second parameter to true.
6. Search for documents
Define a filter: $ filter = array ('name' => 'lily ');
$ Res = $ tables-> Find ($ filter );
Find one: $ res = $ tables-> findone ($ filter );
In addition, you can add a comparison in the filter.
For example, get the information with sessions greater than 10: $ filter = array ('session' => array ('$ GT' => 10 )); (GT --> lt -- <GTE --> = LTE <=) $ cursor = $ collection-> Find ($ filter );
The returned interface is a cursor.
Note that the query is executed only when the result is required. In the 1st example, the query is executed only when the foreach loop starts. This is a very useful feature, because it can be used to retrieve the results by Adding options in the cursor (cursor), just this moment before the query is defined and executed. For example, you can set options to execute pagination,
You can also obtain a specified number of matched documents. $ Total = $ cursor-> total (); $ cursor-> limit (20)-> SKIP (40); foreach ($ cursor as $ user ){}