MongoDB: Inserting, Updating and Deleting Documents

This final chapter in a three-part series will teach you how to insert, update, and delete documents from a collection using MongoDB and PHP.

If the name doesn’t ring any bells, MongoDB (http://www.mongodb.org) is a highly-scalable, document-oriented database written in C++, which permits you to store data by utilizing a JSON-like representation. This means that you can perform CRUD operations (among others) without having to deal with the pitfalls and mismatch issues of an RDBMS, especially when it comes to handling objects, whose state must be persisted in tables.

If you already read the two previous installments of this tutorial, at this stage you should have a clear idea of how to put MongoDB to work for you, as I explained how to install the database on Windows and use its PHP driver to count and fetch sample documents from a collection called “posts”.

MongoDB is capable of running CRUD functions with remarkable ease, implying that it will let you insert, update and remove documents from a collection, thanks to the functionality provided by the brand new “insert()”, “update()” and “remove()” methods bundled with the aforementioned driver.

In this last episode, I’ll be showing you how to accomplish these additional document-related tasks through a set of easy-to-follow code samples.

Adding New Documents to a Collection and Updating Existing Ones: Using the “insert()” and “update()” Methods

Similar to fetching data from a collection, MongoDB makes updating existing documents and inserting new ones a simple process that can be mastered in a jiffy. 

The following code snippet, shows how to update the last document present in the sample “posts” collection created previously. Here it is:

<?php

// example updating a document in the collection

namespace MongoDB;

// connect to the daemon
$mongo = new Mongo();

// select the ‘posts’ collection
$collection = $mongo->selectDB(‘blog’)->selectCollection(‘posts’);

// update the last post
$collection->update(array(‘title’ => ‘My fourth post’), array(‘$set’ => array(‘title’ => ‘My last post’)));

// fetch all posts from the collection
$posts = $collection->find();

foreach ($posts as $post) {
    // display the posts
    echo ‘Id: ‘      . $post['_id']     . ‘<br />
          Title: ‘   . $post['title']   . ‘<br />
          Content: ‘ . $post['content'] . ‘<br />’;
     
    // display the related comments
    foreach ($post['comments'] as $key => $comment) {
        echo $key . ‘ ‘ . $comment . ‘<br />’;
    }
    echo ‘<hr />’;
}

/* displays the following

Id: 4e443c89e4a8497614dcc8d2
Title: My first post
Content: This is the content of the first post
comment 1 This is a sample comment
comment 2 This is another sample comment
comment 3 This is yet another sample comment

Id: 4e443d16e4a8497614dcc8d3
Title: My second post
Content: This is the content of the second post
comment 1 This is a sample comment
comment 2 This is another sample comment
comment 3 This is yet another sample comment

Id: 4e443d36e4a8497614dcc8d4
Title: My third post
Content: This is the content of the third post
comment 1 This is a sample comment
comment 2 This is another sample comment
comment 3 This is yet another sample comment

Id: 4e443d55e4a8497614dcc8d5
Title: My last post
Content: This is the content of the fourth post
comment 1 This is a sample comment
comment 2 This is another sample comment
comment 3 This is yet another sample comment

*/

As seen above, the entire process is reduced to calling the whole new “update()” method and pass into it the field/value pairs that need to be replaced. In addition, it’s worth stressing the use of the “$set” operator (notice “$” character, called the positional operator), which is required for the update to work as intended. It’s possible to utilize the operator in more selective ways. However, doing this is out of the scope of this article, so if you’re interested in the topic, be sure to take a peek at it here (http://www.php.net/manual/en/mongo.updates.php).

So far, so good. As of now, you have learned how to update a document in a collection. Any decent database system should have the ability to insert new documents, and MongoDB certainly isn’t the exception. Moreover, the insertion process can be achieved with a method called  “insert()” too.

The following code sample shows how to use the method in question to add a few more documents to the earlier “posts” collection:
 
<?php

// example inserting new documents into a collection

namespace MongoDB;

// connect to the daemon
$mongo = new Mongo();

// select the ‘posts’ collection
$collection = $mongo->selectDB(‘blog’)->selectCollection(‘posts’);

// create some sample posts
$post1 = array(
    ‘title’    => ‘My fifth post’,
    ‘content’  => ‘This is the content of the fifth post’,
    ‘comments’ => array(
        ‘comment 1′ => ‘This is a sample comment’,
        ‘comment 2′ => ‘This is another sample comment’,
        ‘comment 3′ => ‘This is yet another sample comment’
    )
);

$post2 = array(
    ‘title’    => ‘My sixth post’,
    ‘content’  => ‘This is the content of the sixth post’,
    ‘comments’ => array(
        ‘comment 1′ => ‘This is a sample comment’,
        ‘comment 2′ => ‘This is another sample comment’,
        ‘comment 3′ => ‘This is yet another sample comment’
    )
);

$post3 = array(
    ‘title’    => ‘My seventh post’,
    ‘content’  => ‘This is the content of the seventh post’,
    ‘comments’ => array(
        ‘comment 1′ => ‘This is a sample comment’,
        ‘comment 2′ => ‘This is another sample comment’,
        ‘comment 3′ => ‘This is yet another sample comment’
    )
);

// insert the new posts

$collection->insert($post1);
$collection->insert($post2);
$collection->insert($post3);

// fetch all posts from the collection
$posts = $collection->find();

foreach ($posts as $post) {
    // display the posts
    echo ‘Id: ‘      . $post['_id']     . ‘<br />
          Title: ‘   . $post['title']   . ‘<br />
          Content: ‘ . $post['content'] . ‘<br />’;
     
    // display the related comments
    foreach ($post['comments'] as $key => $comment) {
        echo $key . ‘ ‘ . $comment . ‘<br />’;
    }
    echo ‘<hr />’;
}

echo ‘Number of posts in the collection: ‘ . $collection->count();

/* displays the following

Id: 4e443c89e4a8497614dcc8d2
Title: My first post
Content: This is the content of the first post
comment 1 This is a sample comment
comment 2 This is another sample comment
comment 3 This is yet another sample comment

Id: 4e443d16e4a8497614dcc8d3
Title: My second post
Content: This is the content of the second post
comment 1 This is a sample comment
comment 2 This is another sample comment
comment 3 This is yet another sample comment

Id: 4e443d36e4a8497614dcc8d4
Title: My third post
Content: This is the content of the third post
comment 1 This is a sample comment
comment 2 This is another sample comment
comment 3 This is yet another sample comment

Id: 4e443d55e4a8497614dcc8d5
Title: My last post
Content: This is the content of the fourth post
comment 1 This is a sample comment
comment 2 This is another sample comment
comment 3 This is yet another sample comment

Id: 4e444d11eb60dafc0f000003
Title: My fifth post
Content: This is the content of the fifth post
comment 1 This is a sample comment
comment 2 This is another sample comment
comment 3 This is yet another sample comment

Id: 4e444d11eb60dafc0f000004
Title: My sixth post
Content: This is the content of the sixth post
comment1 This is a sample comment
comment 2 This is another sample comment
comment 3 This is yet another sample comment

Id: 4e444d11eb60dafc0f000005
Title: My seventh post
Content: This is the content of the seventh post
comment1 This is a sample comment
comment 2 This is another sample comment
comment 3 This is yet another sample comment
Number of posts in the collection: 7

*/

Once the batch of new documents has been properly created (in this case three trivial blog posts), the whole insertion method is as simple as invoking the pertinent method and pass to it the document to be appended. 

In the last segment I’ll be setting up another example, which will show how to achieve this by means of a whole new method unsurprisingly called “remove()”.

Creating a Final Example: Removing a Document from the Previous Collection

As I explained in the preceding section, deleting a document from a collection is a simple process reduced to calling the “remove()” method. As usual, the most effective manner to demonstrate how to accomplish this is with a concrete example.

Therefore, below I coded one, which employs the mentioned method for removing the last document in the sample “posts” collection. Have a look at it: 

<?php

// example removing a document from the collection

namespace MongoDB;

// connect to the daemon
$mongo = new Mongo();

// select the ‘posts’ collection
$collection = $mongo->selectDB(‘blog’)->selectCollection(‘posts’);

// delete an existing post
$collection->remove(array(‘title’ => ‘My seventh post’));

// fetch all posts from the collection
$posts = $collection->find();

foreach ($posts as $post) {
    // display the posts
    echo ‘Id: ‘      . $post['_id']     . ‘<br />
          Title: ‘   . $post['title']   . ‘<br />
          Content: ‘ . $post['content'] . ‘<br />’;
     
    // display the related comments
    foreach ($post['comments'] as $key => $comment) {
        echo $key . ‘ ‘ . $comment . ‘<br />’;
    }
    echo ‘<hr />’;
}

echo ‘Number of posts in the collection: ‘ . $collection->count();

/* displays the following

Id: 4e443c89e4a8497614dcc8d2
Title: My first post
Content: This is the content of the first post
comment 1 This is a sample comment
comment 2 This is another sample comment
comment 3 This is yet another sample comment

Id: 4e443d16e4a8497614dcc8d3
Title: My second post
Content: This is the content of the second post
comment 1 This is a sample comment
comment 2 This is another sample comment
comment 3 This is yet another sample comment

Id: 4e443d36e4a8497614dcc8d4
Title: My third post
Content: This is the content of the third post
comment 1 This is a sample comment
comment 2 This is another sample comment
comment 3 This is yet another sample comment

Id: 4e443d55e4a8497614dcc8d5
Title: My last post
Content: This is the content of the fourth post
comment 1 This is a sample comment
comment 2 This is another sample comment
comment 3 This is yet another sample comment

Id: 4e444d11eb60dafc0f000003
Title: My fifth post
Content: This is the content of the fifth post
comment 1 This is a sample comment
comment 2 This is another sample comment
comment 3 This is yet another sample comment

Id: 4e444d11eb60dafc0f000004
Title: My sixth post
Content: This is the content of the sixth post
comment1 This is a sample comment
comment 2 This is another sample comment
comment 3 This is yet another sample comment
Number of posts in the collection: 6

*/

As the previous code bit shows, the “remove()” method resembles its cousins “find()” and “update()”, as it accepts an array as a condition for deleting one or more documents in the collection. In the previous example, the method effectively eliminates the last document, but it’s feasible to specify more generic conditions and remove multiple ones, pretty similar to what you can do with rows in any RDBMS.

With this final example we’ve come to the end of this overview on the main features provided by MongoDB. As always, feel free to play around with all the code samples that you saw before, something that will help you get a more intimate background on the inner workings of the database system.   

Final Thoughts

In this three-part tutorial, I provided you with a humble and succinct introduction to what MongoDB is and how to take advantage of its core functionality in PHP. Although in general object-oriented databases (or document-oriented, in MongoDB parlance) haven’t reached the level of popularity of their relational counterparts, their future look bright and promissory indeed.

Therefore, there’s no better time that now to giving them a try. So, wait are you waiting for? Go head and put MongoDB to work for you! You won’t regret, trust me.

See you in the next PHP development tutorial!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan