<?php
//*************************
* * Connect MongoDB database **//
//*************************
Format = ("mongodb://User name: password @ Address: Port/default specified database", parameters)
$conn = new Mongo ();
can be shortened to
$conn =new Mongo (); #连接本地主机, the 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:[email protected]"); #带用户名密码
$conn =new Mongo ("Mongodb://localhost:27017,localhost:27018″"); #连接多个服务器
$conn =new Mongo ("Mongodb:///tmp/mongo-27017.sock"); #域套接字
$conn =new Mongo ("Mongodb://admin_miss:[email protected]:27017/test", Array (' persist ' = ' P ', "replicaset" = true)); #完整
More information: http://www.php.net/manual/en/mongo.connecting.php
//*************************
* * 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; #更简洁的写法
Note: 1. Databases and collections do not need to be created beforehand and are created automatically if they do not exist.
2. Pay attention to typos, you may inadvertently create a new database (with the original database confusion).
//*************************
* * Insert Document **//
//*************************
* * Insert data into the collection and return bool to determine if 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)
* * Safely inserts data into the collection, returning the Insert State (array). **/
$array =array (' column_name ' = ' col '. Rand (100,999), ' column_exp ' = ' xiaocai2′ ');
$result = $collection->insert ($array, true); #用于等待MongoDB完成操作 in order 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会返回一个记录标识
Var_dump ($result); #返回: Array (3) {["Err"]=> NULL ["n"]=> int (0) ["OK"]=> float (1)}
* * Complete notation **/
#insert ($array, Array (' Safe ' =>false, ' Fsync ' =>false, ' timeout ' =>10000)
/*
* *
* Full format: Insert (array $a [, array $options = Array ()])
* Insert (Array (), Array (' Safe ' =>false, ' Fsync ' =>false, ' timeout ' =>10000)
* Parameters: Safe: Default false, whether secure write
* Fsync: Default false, whether to force insert to sync to disk
* Timeout: Timeout time (milliseconds)
*
* Insert Result: {"_id": ObjectId ("4d63552ad549a02c01000009″"), "column_name": "Col770″," Column_exp ":" Xiaocai "}
* ' _id ' is the primary key field, in the insert is MongoDB automatically added.
*
* Note: 1. The following two insertions are for the same record (same _id) because their values are the same.
* $collection->insert (Array (' column_name ' = ' xiaocai '));
* $collection->insert (Array (' column_name ' = ' xiaocai '));
* Avoid
* $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, similar to the $pull $pullAll $pop $inc, and slowly explain the usage later
/*
Results
* Original Data
* {"_id": ObjectId ("4d635ba2d549a02801000003″"), "column_name": "Col123″," Column_exp ":" Xiaocai "}
* was replaced by a
* {"_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);
/*
Results
* Original Data
* {"_id": ObjectId ("4d635ba2d549a02801000003″"), "column_name": "Col709″," Column_exp ":" Xiaocai "}
* was replaced by a
* {"_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 ' are modified
*/
* * Auto-accumulate **/
$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 auto minus 5
*/
/** Deleting a node **/
$where =array (' column_name ' = ' col685′ ');
$result = $collection->update ($where, Array (' $unset ' = ' column_exp '));
/**
* Delete Node Column_exp
*/
/*
* *
* Full format: Update (array $criteria, array $newobj [, array $options = Array ()])
* Note: 1. Note to distinguish between replacement updates and modification updates
* 2. Note the distinction between data types such as array (' 91u ' = = ' 684435′) with array (' 91u ' =>684435)
* Detailed information: http://www.mongodb.org/display/DOCS/Updating#Updating-%24bit
* *
*/
//*************************
* * Delete Document **//
//*************************
/** emptying the database **/
$collection->remove (Array (' column_name ' = ' col399′ ');
$collection->remove (); #清空集合
/** Delete the specified mongoid **/
$id = new MongoId ("4d638ea1d549a02801000011″");
$collection->remove (Array (' _id ' = = (object) $id));
/*
* *
* Use the following method to match {"_id": ObjectId ("4d638ea1d549a02801000011″)}, same as query, update
* $id = new MongoId ("4d638ea1d549a02801000011″");
* Array (' _id ' = = (object) $id)
* *
*/
//*************************
* * Query Document **//
//*************************
/** 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 (' 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 or 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>";
}
/**
Note
* After we have done the find () operation, the cursor is still dynamic after obtaining the $cursor cursor.
* In other words, after I find (), to my cursor loop to complete this time, if there are more qualifying records are inserted into the collection, then these records will be $cursor obtained.
* If you want the result set to not change after you get $cursor, you need to do this:
* $cursor = $collection->find ();
* $cursor->snapshot ();
* See http://www.bumao.com/index.php/2010/08/mongo_php_cursor.html
*/
/** Query a data **/
$cursor = $collection->findone ();
/**
* Note: FindOne () cannot use functions such as snapshot (), fields () 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'll make an error when I write this: $cursor->fields ("Age" =>true, "type" =>false);
*/
/** (presence type,age node) and age!=0 and age<50 **/
$where =array (' type ' =>array (' $exists ' =>true), ' Age ' =>array (' $ne ' =>0, ' $lt ' =>50, ' $exists ' =>true) );
$cursor = $collection->find ($where);
/** paging Gets the result set **/
$cursor = $collection->find ()->limit (5)->skip (0);
/** Sort **/
$cursor = $collection->find ()->sort (Array (' Age ' =>-1, ' type ' =>1)); # #1表示降序-1 means ascending, and the order of the arguments affects the sort sequence
/** Index **/
$collection->ensureindex (Array (' age ' = 1, ' type ' =>-1)); #1表示降序-1 means ascending
$collection->ensureindex (Array (' age ' = 1, ' type ' =>-1), array (' background ' =>true)); #索引的创建放在后台运行 (default is run synchronously)
$collection->ensureindex (Array (' age ' = 1, ' type ' =>-1), array (' unique ' =>true)); #该索引是唯一的
/**
* Ensureindex (Array (), Array (' name ' = = ' index name ', ' Background ' =true, ' unique ' =true))
* See: http://www.php.net/manual/en/mongocollection.ensureindex.php
*/
/** Get query Results **/
$cursor = $collection->find ();
$array =array ();
foreach ($cursor as $id = = $value) {
$array []= $value;
}
//*************************
* * Document Clustering **//
//*************************
This thing is not clear ...
$conn->close (); #关闭连接
/*
The difference between relational database and MongoDB data storage
MySQL Data structure:
CREATE TABLE IF not EXISTS ' column ' (
' column_id ' int (+) not NULL auto_increment COMMENT ' primary key ',
' column_name ' varchar (+) not NULL COMMENT ' column name ',
PRIMARY KEY (' column_id ')
);
CREATE TABLE IF not EXISTS ' article ' (
' article_id ' int (+) not NULL auto_increment COMMENT ' primary key ',
' article_caption ' varchar (+) not NULL COMMENT ' title ',
PRIMARY KEY (' article_id ')
);
CREATE TABLE IF not EXISTS ' Article_body ' (
' article_id ' int (+) not NULL COMMENT ' article.article_id ',
' Body ' text COMMENT ' text '
);
MONGODB Data structure:
$data =array (
' column_name ' = ' default ',
' Article ' =>array (
' Article_caption ' = ' Xiaocai ',
' Body ' = ' xxxxxxxxxx ... '
)
);
$inc
If the recorded node exists, the value of the node is added to N, and if the node does not exist, the node value equals n
Set the structure record structure to array (' A ' =>1, ' b ' = = ' t '), want to get a plus 5, then:
$coll->update (
Array (' b ' = = ' t '),
Array (' $inc ' =>array (' a ' =>5)),
)
$set
Make a node equal to a given value
The structure record structure is an array (' A ' =>1, ' b ' = ' t ') and B is plus F, then:
$coll->update (
Array (' A ' =>1),
Array (' $set ' =>array (' b ' = ' = ' f ') '),
)
$unset
Delete a node
Set the record structure to array (' A ' =>1, ' b ' = ' t '), and want to delete the B-node, then:
$coll->update (
Array (' A ' =>1),
Array (' $unset ' = ' B '),
)
$push
If the corresponding node is an array, append a new value to it, create the array and append a value to the array if it is not, and return an error if the node is not.
Set the record structure to array (' A ' =>array (0=> ' haha '), ' B ' =& gt;1), and want to append the new data to Node A, then:
$coll->update (
Array (' B ' =>1),
Array (' $push ' =>array (' a ' + = ' wow ')),
)
In this way, the record becomes: Array (' A ' =>array (0=> ' haha ',1=> ' wow '), ' B ' =>1)
$pushAll
Similar to $push, except that multiple values are appended to a node at a time
$addToSet
If there is no value in the array for that stage, add the
Set the record structure to array (' A ' =>array (0=& gt; ' Haha '), ' B ' =>1), if you want to append the new data to the Node A, then:
$coll->update (
Array (' B ' =>1),
Array (' $addToSet ' =>array (' a ' + = ' wow ')),
)
If WOW is already in the a node, no new additions are added, and if not, a new item--wow is added to the node.
$pop
Set this record as an array (' A ' =>array (0=> ' haha ',1=& gt; ') Wow '), ' B ' =>1)
Delete the last element of an array node:
$coll->update (
Array (' B ' =>1),
Array (' $pop =>array (' a ' =>1)),
)
Delete the first element of an array stage
$coll->update (
Array (' B ' =>1),
Array (' $pop =>array (' a ' =>-1)),
)
$pull
If the node is an array, then deleting the subkey whose value is values, or if it is not, returns an error.
Set the record as array (' A ' =>array (0=> ' haha ',1=> ' wow '), ' B ' =>1), and want to delete the subkey of value in a (haha):
$coll->update (
Array (' B ' =>1),
Array (' $pull =>array (' a ' = ' = ' haha ')),
)
The result is: Array (' A ' =>array (0=> ' wow '), ' B ' =>1)
$pullAll
Similar to $pull, you can delete only a set of qualifying records.
*/
?>
Transfer from http://www.cnblogs.com/jackluo/archive/2013/06/16/3138835.html