Home arrow PHP arrow MongoDB: Working with Documents and Collections

MongoDB: Working with Documents and Collections

This article continues our look at MongoDB. This time, we will be showing you how to count and retrieve documents from a collection.

By: Alejandro Gervasio
Rating: starstarstarstarstar / 0
September 15, 2011

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

If you think that the group of RDBMS' out there fall short when it comes to persisting the host of objects that comprise your applications, maybe it is time to get rid of the constraints imposed by relational databases and take a look at MongoDB (http://www.mongodb.org), a schema-less, document-oriented database written in C++, which lets you store your carefully-crafted objects by using a JSON-like representation known as BSON (http://bsonspec.org).

Although it’s fair to admit that object-oriented databases don't have much of a presence in the terrain of web development, which is in most cases ruled by the forces of RDBMS, the truth is that some contenders are starting to step up to the plate. Good examples of this trend are CouchDB (http://couchdb.apache.org/index.html) and the aforementioned MongoDB, which currently offers drivers for a great variety of programming languages, including C, C#, Java, Ruby, PHP and so forth.

Of course, my intention here is to provide you with a quick overview of the latter and how you can make it work hand in hand with PHP. In line with this idea, in the introductory chapter of this tutorial I explained how to install MongoDB on Windows, and went through the process of creating a sample database and a collection, which was populated with a few trivial documents. If you missed this article, you can find it here:

http://www.devshed.com/c/a/PHP/MongoDB-A-Free-DocumentOriented-Database-19104/

With this base configuration already set, I built a couple of scripts which showed how to connect to the database daemon and how to fetch the corresponding documents from the sample collection by using the “findOne()” and “find()” methods included with MongoDB’s PHP driver.

Naturally, the database is capable of performing many other tasks aside from the ones mentioned above, including the ability for counting documents in a collection and retrieving them according to a given condition. Thus, in this second installment I’ll be demonstrating how to accomplish this.

MongoDB: Counting Documents in a Collection

If I ever had to describe MongoDB’s PHP API, I would do so with one word: simplicity. Once you’ve managed to create a database and at least a non-empty collection, a process that I discussed in detail in the first part of this series, fetching documents is as simple as calling the API’s “findOne()” and “find()” methods. It’s really that easy.

As I said in the introduction, however, in many use cases you’ll need to do a few other things, such as calculating the number of documents present in a collection (the equivalent to counting rows in a RDBMS). Not surprisingly, MondoDB provides a method called “count()”, which allows you to perform this task in a straightforward fashion.

Logically, the best way to demonstrate the use of “count()” is with a concrete example. So, below I coded one, which utilizes the “blog” database and the “posts” collection created in the preceding article.

The example in question looks like this:

<?php

// example fetching and counting all documents from a collection

namespace MongoDB;

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

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

// 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 fourth 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
Number of posts in the collection: 4

*/

Quite similar to the examples you learned in the introductory article, this one starts out connecting to the server and selecting the “blog” and “posts” collection respectively. Once this has been done, all of the stored documents are retrieved with the “find()” method and echoed to the screen via a “foreach” construct. While this retrieval process is quite simple to follow, you should note how easy it is to call the aforementioned “count()” method, in order to display the number of documents that exist in the collection (four, in this particular case).

Undeniably, understanding the logic that stands behind “count()” is a breeze. Therefore, it’s time to move on and do something a bit more useful with MongoDB. So far, I demonstrated the functionality of the “findOne()” and “find()” methods, which as you saw previously, permit you to fetch the first document in a collection.

In most cases, though, it’s necessary to fetch a set of documents that match a given condition (otherwise, you’ll end up dumping the entire collection, which is pretty pointless for obvious reasons). But, does this mean that MongoDB doesn’t support conditional queries? Well, fear not, as it’s possible to pass in a condition to the same “find()” method and get only the documents that meet it.

Furthermore, in the following segment I’ll be coding a final example, which will demonstrate how to perform a conditional query with the already familiar “posts” collection.      

Fetching Documents in a Collection that Match a Specified Condition

As I expressed in the previous segment, MongoDB makes it really easy to perform conditional queries. What’s more, the whole process is reduced to passing in a condition in the form of an array when calling the “find()” method and nothing more.

As usual, the best way to understand how to accomplish this is by example. Therefore, I suggest you have a look at the following one, which uses the method in question for fetching only the second document in the sample “posts” collection. Check it out:

<?php

// example fetching documents from a collection according to a given condition

namespace MongoDB;

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

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

// fetch all posts from the collection that match the given predicate
$posts = $collection->find(array('title' => 'My second post'));

foreach ($posts as $post) {
    // display the post(s)
    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: 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

*/

By specifying a predicate (in this case, the condition 'title' => 'My second post') when invoking the “find()” method, it makes it extremely simple to retrieve only the document(s) that meet the given condition. In the example above, the process returned only one document, which logically is the expected behavior. It’s possible, however, to call the pertinent method with a different criterion and obtain a subset of the original collection.

And with this final example, we’ve come to the end of this second chapter of our tutorial. As always, feel free to tweak the code samples that you saw before, something that surely will arm you with a better understanding of MongoDB and how to get it working with PHP.

Final Thoughts

In this follow up on MongoDB, things were much more exiting, as you learned (or that was my humble purpose from the start) how to count the number of documents existing in a collection, and how to fetch them selectively. In both cases, the process was as simple as calling the “count()” and “find()” methods, even though specifying a condition for the latter.

In the final episode, I’m going to show you how to add new documents to a collection, as well as how to update and remove existing ones in a snap. Not surprisingly, these operations will be carried out by two methods provided by the database API, called “insert()”, “update()” and “remove()”.

Don’t miss the last part!


 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: