CRUD in Mongodb with PHP
In last post we introduced how to install mongodb and the php extension on windows.
Lets do some CRUD operation in PHP script.
Select a collection is just like select a database:
$conn = new Mongo(); $db = $conn->selectDB('testdb'); $collection = $db->myc;
The collection can be exist or not exist, no matter what, you will get a collection, it may be the existing one or the created one.
Its almost trivial, just define an array and insert it.
The foreach will print all the documents in collection.
Array ( [_id] => MongoId Object ( [$id] => 5188bead7ab2adec27000000 ) [title] => this is title [content] => this is content [category] => database ) Array ( [_id] => MongoId Object ( [$id] => 5188beb77ab2ad7805000000 ) [title] => this is title [content] => this is content [category] => database )
As you can see Mongodb use an unique id to identify each document .
Find a document by id:
Its very similar to SQL select statements
SELECT * FROM collection WHERE _id = $id
You can also select by other keys:
$results = $collection->findone(array( 'title' => 'this is title', ));
The SQL simulation
SELECT * FROM collection WHERE title = 'this is title'
How about select particular columns
The second array is the columns that need to returned .
The $set tells Mongodb its an update, not replace the whole document.
The update can not only update the existing column, but also add new columns:
Array ( [_id] => MongoId Object ( [$id] => 5188bebf7ab2ad7422000000 ) [category] => database [content] => update content [keywords] => Array (  => name  => mongo  => software  => web ) [title] => this is title )
This is not what you can easily do in a relational database.