* Sources : http://www.jbistory.net/
mongoDB를 PHP에서 사용하는 방법을 알아보자!
본인의 경우 mysql 만 써오다보니 mongoDB 사용법이 별거 아니었음에도 불구하고 한참이나 헤멨었기에.. 본인이 기억하기 위해서라도 간단하게 포스팅을 해본다.
위에 링크를 기재하였듯이 원문은 Sources : http://www.jbistory.net/ 에서 가져온 것이다.
Here’s a couple links to get you up to speed:
Installing Mongo
MongoDB PHP Extension
If you have issues with MongoD not starting – something about “/data/db” missing, then you should create the directory. In *Nix: “mkdir /data/db”, in Win “mkdir c:data” then “mkdir c:datadb”.
대략 해당 튜토리얼은 단순히 mongoDB나 NoSQL에 관한것이 아니라 다른 스타일의 튜토리얼이라고 말하고 있는듯 하다. 확실히 해당 튜토리얼은 설명이 난무한 그런 안타까운 튜토리얼이 아닌 실제 코드들로 비교하고 있는,
참 아름다운 튜토리얼이다. 본인 생각에는 말이다!
그럼 차근차근 DB 연결부터 데이터의 삽입, 갱신, 삭제를 거쳐 DB 연결해제까지 MySQL 코드와 비교해가면서 살펴보도록 하자. MySQL 을 써본 사람이라면 정말 쉽게! 바로 이해하고 사용할 수 있을 것이다.
1. Connecting DB
$host = ‘localhost’;
$user = ‘root’;
$pass = “”;
$link = mysql_connect($host, $user, $pass, 1) or die(“Could not connect to: {$host}. Check your settings and try again.”);
try{
$link = new Mongo();
} catch(MongoConnectionException $e) {
die(‘Could not connect. Check to make sure MongoDB is running.’);
}
2. Creating and using a DB
$db = ‘testdb’;
$sql = “CREATE DATABASE `$db`”;
mysql_query($sql, $link);
mysql_select_db($db, $link);
[MongoDB]
$db = $link->testdb;
In one line of code, MongoDB will create a DB automatically if it doesn’t already exists and select (use) it.
Create a Table / Collection
3. Create the Table(Collection)
$tbl = ‘user’;
$sql = “CREATE TABLE `$tbl` (`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, `login` VARCHAR (24)NOT NULL, `password` CHAR(32) NOT NULL, `email` VARCHAR(255)) TYPE=innodb;”;
mysql_query($sql, $link);
$col = $db->user;
Insert Data
4. Insert a row(document) into the table(Collection)
$sql = “INSERT INTO `$tbl` SET `login` = ‘jsmith’, `password` = ’5f4dcc3b5aa765d61d8327deb882cf99′, `email` = ‘jsmith@example.com’”;
mysql_query($sql);
$sql = “INSERT INTO `$tbl` SET `login` = ‘psmith’, `password` = ’5f4dcc3b5aa765d61d8327deb882cf99′, `email` = ‘psmith@example.com’”;
mysql_query($sql);
$doc = array(‘login’ => ‘jsmith’, ‘password’ => ‘ 5f4dcc3b5aa765d61d8327deb882cf99′, ‘email’ => ‘jsmith@example.com’);
$col->insert($doc, true);
$doc = array(‘login’ => ‘psmith’, ‘password’ => ‘ 5f4dcc3b5aa765d61d8327deb882cf99′, ‘email’ => ‘psmith@example.com’);
$col->insert($doc, true);
You might have noticed that we used an array to define our “row” of data, which are called “documents”. On the insert method, the second argument will set the query to do a “safe insert”. This will allow us to find out if the query executed properly. If not set, it will not get that information. So I would set it to true if you want to be able to debug your queries. If you are wondering about the password, it’s the MD5 hash for “password”.
Querying Data
5. Get All row(Document)
// Get all row
$sql = “SELECT * FROM `$tbl`”;
$qry = mysql_query($sql, $link);
$cnt = mysql_num_rows($qry);
echo ‘All rows:<br/>’;
if($cnt > 0) {
do {
$row = mysql_fetch_assoc($qry);
echo ‘<pre>’;
print_r($row);
echo ‘</pre>’
}
}
// Query for the row matching the last insert ID
$sql = “SELECT * FROM `$tbl` WHERE `id` = {$id}”;
$qry = mysql_query($sql, $link);
$row = mysql_fetch_assoc($qry);
echo ‘Single row (id = $id):<br/><pre>’;
print_r($row);
echo ‘</pre>
// Get all documents
$res = $col->find();
echo ‘All documents:<br/>’;
foreach($res as $doc){
echo ‘<pre>’;
print_r($doc);
echo ‘</pre>’;
}
// Query for the document matching the last insert ID
$doc = $col->findone(array(‘_id’ => $id));
echo ‘Single document (_id = $id):<br/><pre>’;
print_r($doc);
The MongoDB support in PHP has function to pull a single document, or all the documents. Once again, we use arrays to define something, in this example, we define our constraint.
6. Updating Data
$sql = “UPDATE `$tbl` SET `password` = ‘b497dd1a701a33026f7211533620780d’ WHERE `id` = {$id}”;
$qry = mysql_query($sql, $link);
$sql = “SELECT * FROM `$tbl` WHERE `id` = {$id}”;
$qry = mysql_query($sql, $link);
$row = mysql_fetch_assoc($qry);
echo ‘Updated row (id = $id):<br/><pre>’;
print_r($row);
echo ‘</pre>
// Update a document
$col->update(array(‘_id’ => $id), array(‘$set’ => array(‘password’ => ‘b497dd1a701a33026f7211533620780d’)));
// Query the updated docuemnt
$doc = $col->findone(array(‘_id’ => $id));
echo ‘Updated docuement:<br/><pre>’;
print_r($doc);
echo ‘</pre>’;
The MongoDB extension has a function to perform updates. The first argument is an array of constraints, IE “WHERE {expression}”. The second is the data we want to update and what we want to update it with. Pretty simple, right?
* ->update(검색조건, 업데이트내용 , true) 로 써줄 경우,
update 수행 시 update 할 내용이 존재하면 update, 없을 경우에는 insert 기능 수행
7. Indexing Data
// Create a unique index
$sql = “ALTER TABLE `$db`.`$tbl` ADD UNIQUE `login` (`login`)”;
$qry = mysql_query($sql, $link);
// Create a unique index
$col->ensureIndex(array(“login” => 1), array(“unique” => true, “dropDups” => true));
MongoDB has method for creating index name “ensureIndex”. The first parameter is an array of what we want to index and the value is ether 1 or -1. 1 means that the index will sort the data for this in an ascending manor, while -1 will sort it in a descending manor. The second parameter are extra options. In this example I tell it to make what ever I’m indexing as a unique index, that way I don’t end up with multiple “jsmith” entries. Also, I’ve told it to drop any documents that have duplicates of the data in the “login” “column”. Another note is that “columns” in MongoDB should be called “elements”, since we are really dealing with arrays.
Lets make sure our index is working shall we?
// Test our unique index
try {
$doc = array(‘login’ => ‘jsmith’, ‘password’ => ‘ 5f4dcc3b5aa765d61d8327deb882cf99′);
$col->insert($doc, true);
} catch(MongoCursorException $e) {
echo ‘Could not insert document. Double check values.<br />’;
}
If all works, we should get an error message.
8. Limiting Results
// Limits
$sql = “SELECT * FROM `$tbl` LIMIT 1″;
$qry = mysql_query($sql, $link);
$cnt = mysql_num_rows($qry);
echo ‘All rows – Limit by 1:<br/>’;
if($cnt > 0) {
do {
$row = mysql_fetch_assoc($qry);
echo ‘<pre>’;
print_r($row);
echo ‘</pre>’
}
}
// Limits
$res = $col->find()->limit(1);
echo ‘All documents – Limited to 1:<br/>’;
foreach($res as $doc) {
echo ‘<pre>’;
print_r($doc);
echo ‘</pre>’;
}
9. Offsetting
// Limits
$sql = “SELECT * FROM `$tbl` OFFSET 1 LIMIT 1″;
$qry = mysql_query($sql, $link);
$cnt = mysql_num_rows($qry);
echo ‘All rows – Limit by 1 – Offset by 1:<br/>’;
if($cnt > 0) {
do {
$row = mysql_fetch_assoc($qry);
echo ‘<pre>’;
print_r($row);
echo ‘</pre>’;
}
}
// Offsets
$res = $col->find()->skip(1)->limit(1);
echo ‘All documents – Limited to 1, Offset by 1:<br/ >’;
foreach($res as $doc) {
echo ‘<pre>’;
print_r($doc);
echo ‘</pre>’;
}
To offset a your query start point, we used the method “skip” with an integer value to create the offset.
10. Sorting
// Sorting
$sql = “SELECT * FROM `$tbl` ORDERBY `login` DESC”;
$qry = mysql_query($sql, $link);
$cnt = mysql_num_rows($qry);
echo ‘All rows – Sorted by login descending:<br/>’;
if($cnt > 0) {
do {
$row = mysql_fetch_assoc($qry);
echo ‘<pre>’;
print_r($row);
echo ‘</pre>’
} while(–$cnt > 0);
}
// Sorting
$res = $col->find()->sort(array(‘login’ => -1));
echo ‘All documents – Sorted by login descending:<br/>’;
foreach($res as $doc) {
echo ‘<pre>’;
print_r($doc);
echo ‘</pre>’;
}
Here we used the sort method, told it what element to sort on and which direction, -1 being descending. The record for “psmith” should show up first. A word of caution here, there is a 4MB limit if sorting on non-indexed element.
더보기
11. Deleting a Row (Document)
// Delete a row
$sql = “DELETE FROM `$tbl` WHERE `login` = ‘psmith’”
mysql_query($sql, $link);
// Delete a document
$col->remove(array(‘age’ => 24), array(‘justOne’ => true, ‘safe’ => true));
Here we use the “remove” method. First argument has the constraints and the second tell it to only remove one item and also to run a “safe” query.
12. Deleting a Table (Collection)
// Drop table
$sql = “DROP TABLE `$db`.`$tbl`”;
mysql_query($sql, $link);
// Drop collection
$col->drop();
13. Deleting a Database
// Drop DB
$sql = “DROP DATABASE `$db`”;
mysql_query($sql, $link);
// Drop DB
$db->drop();
14. Disconnect
// Disconnect
mysql_close($link);
// Disconnect
$link->close();
이정도 튜토리얼을 따라해봤다면 mysql 쓰듯이 나름 다양하고 편리하게 mongoDB를 사용할 수 있지 않을 까 생각된다!
NoSQL 이 트랜드인 요즘인 만큼!(좀 트랜드가 된지 오래된 듯도 하지만..)
한번쯤 써보는 것도 나쁘진 않을 듯하다!!
* SQL 과 MongoDB 의 Mapping 에 대해 좀더 보고 싶다면! 이곳을 참고하자!
그럼, 해피코딩!!
'DB,SQL' 카테고리의 다른 글
Redis 기초 명령어 (0) | 2014.03.25 |
---|---|
ZooKeeper를 활용한 Redis Cluster 관리 (0) | 2014.03.21 |
php와 mongodb 연동 (0) | 2014.03.05 |
mongoDB php연동 (0) | 2014.03.05 |
mongoDB dbshell 레퍼런스 (0) | 2014.03.05 |