PHP Operation MongoDB Configuration and learning notes

Source: Internet
Author: User
Tags foreach create index findone mongodb rand sort

2, install (Windows only)
Download the corresponding package to the official website
Extract to D:mongodb
Create d:mongodbdata Drop Data file

3, Run MongoDB
D:mongodbbin There are executable files, where Mongod.exe is the server side, Mongo.exe is the client.
Run cmd, enter
D:mongodbbin>mongod.exe-dbpath D:mongodbdata
Server started successfully

4, let PHP support MongoDB
Download Php_mongo.dll, pay attention to version, php5.3.x should support V9 (some old data let Apache V6, in fact, to see phpinfo download the corresponding version);
Modify php.ini, increase extension = Php_mongo.dll;
Restart Apache.

The code is as follows Copy Code

<?php
/**
* PHP Operation MongoDB Learning Notes
* February 23, 2011
* Original Author: Xiaocai
*/

//*************************
* * Connect to MONGODB database server
//*************************

Format => ("mongodb://Username: password @ address: Port/default specified database", parameters)
$conn = new Mongo ();
can be abbreviated to
$conn =new Mongo (); #连接本地主机, default port.
$conn =new Mongo ("172.21.15.69"); #连接远程主机
$conn =new Mongo ("xiaocai.loc:10086"); #连接指定端口远程主机
$conn =new Mongo ("Xiaocai.loc", Array ("Replicaset" =>true)); #负载均衡
$conn =new Mongo ("Xiaocai.loc", Array ("persist" => "T")); #持久连接
$conn =new Mongo ("Mongodb://sa:123@localhost"); #带用户名密码
$conn =new Mongo ("mongodb://localhost:27017,localhost:27018"); #连接多个服务器
$conn =new Mongo ("Mongodb:///tmp/mongo-27017.sock"); #域套接字
$conn =new Mongo ("Mongodb://admin_miss:miss@localhost:27017/test", Array (' Persist ' => ' P ', "Replicaset" =>   true)); #完整

//*************************
* * Select database and table
//*************************

$db = $conn->mydb; #选择mydb数据库
$db = $conn->selectdb ("MyDB"); #第二种写法

$collection = $db->column; #选择集合 (SELECT ' table ')
$collection = $db->selectcollection (' column '); #第二种写法
$collection = $conn->mydb->column; #更简洁的写法

Attention:
1. Databases and collections do not need to be created beforehand, and they are created automatically if they do not exist.
2. Note Typos, you may inadvertently create a new database (with the original database confusion).


//*************************
* * Insert Document
//*************************

* * Inserts data into the collection, returns bool to determine whether the insert succeeded. **/
$array =array (' column_name ' => ' col '. Rand (100,999), ' column_exp ' => ' Xiaocai ');
$result = $collection->insert ($array); #简单插入
echo "New record ID:". $array [' _id ']; #MongoDB会返回一个记录标识
Var_dump ($result); #返回: BOOL (TRUE)
#插入结果: {"_id": ObjectId ("4d63552ad549a02c01000009"), "column_name": "col770", "Column_exp": "Xiaocai"}
# ' _id ' is the primary key field, where the insert is MongoDB automatically added.

//** inserts the data safely into the collection, returning the Insert State (array). **/
$array =array (' column_name ' => ' col '. Rand (100,999), ' Column_exp ' => ' Xiaocai2 '); The
$result = $collection->insert ($array, True);   #用于等待MongoDB完成操作 to determine whether it was successful. (This parameter is useful when you have a large number of records inserted)
Echo new record ID: ". $array [' _id '];             ] MongoDB returns a record identification
Var_dump ($result);                           #返回: Array (3) {["Err"]=> NULL ["N "]=> Int (0) [" OK "]=> float (1)}
   
//** inserted complete syntax **/
# Insert (array $data, array (' Safe ' =& Gt;false, ' Fsync ' =>false, ' timeout ' =>10000) '
# parameter Description: Safe: Default false, Safe write, Fsync: default false, force insert to disk; Timeout: Timeout time (ms)

* * The following two inserts are the same record (the same _id) because their values are the same **/
$collection->insert (Array (' column_name ' => ' Xiaocai '));
$collection->insert (Array (' column_name ' => ' Xiaocai '));
#避免方法, safe insertion
$collection->insert (Array (' column_name ' => ' Xiaocai '), true);
try {
$collection->insert (Array (' column_name ' => ' Xiaocai '), true);
}catch (Mongocursorexception $e) {
echo "Can ' t Save the same person twice!n";
}
Detailed information: http://www.php.net/manual/zh/mongocollection.insert.php


//*************************
* * Update document
//*************************

* * Modify Update **/
$where =array (' column_name ' => ' col123 ');
$newdata =array (' column_exp ' => ' ggggggg ', ' Column_fid ' =>444);
$result = $collection->update ($where, Array (' $set ' => $newdata)); # $set: Make a node equal to a given value
/*
* Original Data
* {"_id": ObjectId ("4d635ba2d549a02801000003"), "column_name": "col123", "Column_exp": "Xiaocai"}
* has been replaced
* {"_id": ObjectId ("4d635ba2d549a02801000003"), "column_name": "col123", "Column_exp": "Ggggggg", "Column_fid": 444}
*/

* * Replace update **/
$where =array (' column_name ' => ' col709 ');
$newdata =array (' column_exp ' => ' hhhhhhhhh ', ' Column_fid ' =>123);
$result = $collection->update ($where, $newdata);
/*
* Original Data
* {"_id": ObjectId ("4d635ba2d549a02801000003"), "column_name": "col709", "Column_exp": "Xiaocai"}
* has been replaced
* {"_id": ObjectId ("4d635ba2d549a02801000003"), "Column_exp": "Hhhhhhhhh", "Column_fid": 123}
*/

* * Batch update **/
$where =array (' column_name ' => ' col ');
$newdata =array (' column_exp ' => ' multiple ', ' 91u ' =>684435);
$result = $collection->update ($where, Array (' $set ' => $newdata), array (' multiple ' =>true));
/**
* all ' column_name ' = ' col ' have been modified
*/

* * Automatic Cumulative **/
$where =array (' 91u ' =>684435);
$newdata =array (' column_exp ' => ' edit ');
$result = $collection->update ($where, Array (' $set ' => $newdata, ' $inc ' =>array (' 91u ' =>-5));
/**
* Update 91u=684435 data and 91u self minus 5
* Note: 91u exists with 5, set 91u=-5 when it does not exist
*/

* * Match to be updated, otherwise add **/
$c->update (
Array ("name" => "Joe"),
Array ("username" => "joe312", "Createdat" => New Mongodate ()),
Array ("Upsert" => True) #up (date) (in) SERT
);

/** Delete Node **/
$where =array (' column_name ' => ' col685 ');
$result = $collection->update ($where, Array (' $unset ' => ' column_exp '));
/**
* Delete Node Column_exp
*/

/** append new data to Node **/
$coll->update (
Array (' B ' =>1),
Array (' $push ' =>array (' a ' => ' wow ') #附加新数据到节点a
);
# if the corresponding node is a number, append a new value to it; if it does not exist, create the array and append a value to the array;
# If the node is not an array, returns an error.
# Original record: Array (' A ' =>array (0=> ' haha '), ' B ' =>1)
# The new record is: Array (' A ' =>array (0=> ' haha ',1=> ' wow '), ' B ' =>1)
# $pushAll similar to $push, just append multiple values to a node at a time

/** Judgment Update **/
$coll->update (
Array (' B ' =>1),
Array (' $addToSet ' =>array (' a ' => ' wow '))
);
# If there is not a value in the array of the stage, add it
# set record structure to array (' A ' =>array (0=> ' haha '), ' B ' =>1)
# If WOW is already in a node, then no new one will be added.
# if not, a new item--wow will be added to the node.

/** deletes the last element of an array node **/
$coll->update (
Array (' B ' =>1),
Array (' $pop ' =>array (' a ' =>1) #删除a数组节点的最后一个元素
);

/** deletes the first element of an array node **/
$coll->update (
Array (' B ' =>1),
Array (' $pop ' =>array (' a ' =>-1) #删除a数组节点的第一个元素
);

/** deletes an element of an array node **/
$coll->update (
Array (' B ' =>1),
Array (' $pull ' =>array (' a ' => ' haha '))
)
# If the node is an array, then the subkey whose value is values is deleted, and an error is returned if it is not a list.
# The original record is: Array (' A ' =>array (0=> ' haha ',1=> ' wow '), ' B ' =>1),
# Delete subkeys in a with value haha
# Result: Array (' A ' =>array (0=> ' wow '), ' B ' =>1)
# $pullAll Similar to $pull, you can simply delete a set of records that meet the criteria.

Attention
# 1. Note to distinguish between replacement updates and modification updates
# 2. Note Distinguishing between data types such as array (' 91u ' => ' 684435 ') and Array (' 91u ' =>684435)

//*************************
* * Delete Document
//*************************

/** Delete **/
$collection->remove (Array (' column_name ' => ' col399 '));
$collection->remove (); #清空集合
$collection->drop (); #清空, more efficient than remove ()


/** deletes the specified mongoid **/
$id = new Mongoid ("4d638ea1d549a02801000011");
$collection->remove (Array (' _id ' => (object) $id));
/*
* *
* Use the following method to match {"_id": ObjectId ("4d638ea1d549a02801000011")}, query, update also
* $id = new Mongoid ("4d638ea1d549a02801000011");
* Array (' _id ' => (object) $id)
* *
*/


//*************************
* * Query Documents
//*************************

/** the number of records in the query document **/
Echo ' Count: '. $collection->count (). "                                          <br> "; #全部
Echo ' Count: '. $collection->count (Array (' type ' => ' user ')). "                     <br> "; #可以加上条件
Echo ' Count: '. $collection->count (Array (' Age ' =>array (' $gt ' =>50, ' $lte ' =>74)). " <br> "; #大于50小于等于74
Echo ' Count: '. $collection->find ()->limit (5)->skip (0)->count (true).           <br> "; #获得实际返回的结果数

/**
* Note: $GT is greater than, $GTE is greater than or equal to, $lt is less than, $lte is less than equal, $ne is not equal to, $exists does not exist
*/

/** all documents in the collection **/
$cursor = $collection->find ()->snapshot ();
foreach ($cursor as $id => $value) {
echo "$id:"; Var_dump ($value); echo "<br>";
}
/**
Attention
* After we do the find () operation and get the $cursor cursor, the cursor is still dynamic.
* In other words, after I find (), by the time my cursor loop completes, if the qualifying records are inserted into the collection, then the records will be $cursor.
* If you want the result set to be $cursor after you get it, you need to do this:
* $cursor = $collection->find ();
* $cursor->snapshot (); #获得快照!
* Refer to Http://www.bumao.com/index.php/2010/08/mongo_php_cursor.html
*/

/** query a piece of data **/
$cursor = $collection->findone ();
/**
* Note: FindOne () can not use Snapshot (), fields () and other functions after obtaining the result set;
*/

/** age,type column does not display **/
$cursor = $collection->find ()->fields (Array ("Age" =>false, "type" =>false));

/** displays only the user column **/
$cursor = $collection->find ()->fields (Array ("user" =>true));
/**
* I write this error: $cursor->fields (Array ("Age" =>true, "type" =>false));
*/

/** (presence of type,age nodes) and age!=0 and age<50 **/
$where =array (' type ' =>array (' $exists ' =>true), ' Age ' =>array (' $ne ' =>0, ' $lt ' =>50, ' $exists ' =>true) );
$cursor = $collection->find ($where);

/** page to get result set **/
$cursor = $collection->find ()->limit (5)->skip (0);

/** Sort **/
$cursor = $collection->find ()->sort (Array (' Age ' =>-1, ' type ' =>1)); #1表示降序-1 for ascending, and the order of the parameters affects the sort orders

/** CREATE INDEX **/
$collection->ensureindex (Array (' Age ' => 1, ' type ' =>-1)); #1表示降序-1 indicates ascending
$collection->ensureindex (Array (' Age ' => 1, ' type ' =>-1), array (' background ' =>true)); #索引的创建放在后台运行 (synchronous run by default)
$collection->ensureindex (Array (' Age ' => 1, ' type ' =>-1), array (' unique ' =>true)); #该索引是唯一的

/** Get query Results **/
$cursor = $collection->find ();
$array =array ();
foreach ($cursor as $id => $value) {
$array []= $value;
}

Related Article

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.