MongoDB driver tips & tricks: PHP

A large proportion of support requests to MongoLab are questions about how to properly configure and use a particular MongoDB driver.

This blog post is the third of a series where we are covering each of the major MongoDB drivers in depth. The driver we'll be covering here is the PHP driver, developed and maintained by the MongoDB, Inc. team (primarily @derickr, @bjori and @jmikola).

In this post:

The PHP MongoDB driver

This post aims to help you understand how to configure and use the PHP driver effectively in your MongoDB application. For your reference, you can find the complete documentation for the PHP driver on the PHP community site.

A simple PHP example

You can find a straightforward example on connecting, inserting, updating and querying using the PHP driver in MongoLab's Language Center.

Production-ready connection settings

We often see incorrect configurations of the driver, particularly around timeouts and replica set connections. To help you connect to MongoLab (or any cloud MongoDB) using the PHP driver, we've provided the following MongoLab-recommended settings:

Additional connection options that are supported by the PHP driver can be found here.

PHP driver tips & tricks

Index builds can sometimes block new connections

When establishing a connection to a MongoDB replica set, the driver first attempts to connect and authenticate to each non-hidden node in the cluster. If a node is "down", it will be passed over. However, if a node is "up" but holding the write lock such that the 'authenticate' command cannot execute, the driver will then hang. This is common when building indexes since, in all MongoDB versions before 2.6,  all index builds (background or foreground) will build in the foreground on secondaries.

In version 1.5.3 of the PHP driver (to be released soon) there will be an improvement that allows the driver to bypass authentication to the secondary node building an index. Please note that this only applies if the secondary is undergoing an Initial Sync. A further release will address this issue during any type of foreground index build.

Consider lowering is_master_interval from its default

For applications with demanding availability requirements, we recommend examining the default PHP driver runtime configuration settings (set in the php.ini file). In particular, the mongo.is_master_interval option controls how quickly the driver can recover after replica set cluster elections.

The is_master_interval option (default: 15 seconds) sets the interval that the driver sends "isMaster" requests to each mongod instance. These requests help the driver determine the topology of the replica set; specifically, the request checks to see if a specific node is the primary and can receive writes.

We recommend experimenting with lowering this value to 1 or 2 seconds so that your driver can quickly locate a primary after an election or failover. Of course, depending on how many clients you have you will want a value that does not ping your servers too often.

Also keep in mind that when an election or failover results in a change in the primary server, there will always be a few seconds where your driver will receive a "MongoConnectionException" with message "No candidate servers found." It's important to handle these exceptions in your code so that your application does not terminate.

Understand how connections are handled and configure connectionTimeoutMS

The PHP driver does not use connection pooling. Therefore it is recommended that you create one connection to your database per PHP process.

However, if you are building a web application it is likely that you will have many PHP worker processes (and in the worst-case a new PHP process per HTTP request). This creates a scenario where you are potentially creating a lot of new database connections, since the PHP driver cannot share connections between processes. Because of this, PHP apps can be especially vulnerable to temporary conditions that  impede the creation of initial database connections (network blips, busy servers, etc...).

To help in this regard we recommend that you customize the connectionTimeoutMS option and be aware of the mongo.ping_interval option in php.ini.


The PHP driver does not explictly define a default connection timeout. Instead, the default value is determined by the default_socket_timeout setting in the php.ini file (default: 60 seconds). With this default, your driver will wait up to 60 seconds while connecting before timing out. Given that each request may have to endure this timeout, you may want to lower it.

We highly recommend explicitly setting the connectionTimeoutMS option via connection string URI options.  One approach is to experiment with values between 5 to 30 seconds.  Another approach would be to configure your connection timeout to 1 second and then upon retry progressively increase the timeout value to 30 seconds.


The second setting to be aware of is mongo.ping_interval, which is set in the php.ini file and has a default value of 5 seconds. This option sets the interval that the driver sends ping requests to each mongod instance to find a "down" node. mongo.ping_interval is used in conjunction with the PHP driver's concept of a server "blacklist", which tracks these "down" nodes.

The PHP driver server "blacklist" tells the driver which nodes it should ignore (not connect to) for ping_interval seconds. In a case where the ping_interval value is 5, the driver will attempt to connect to a "down" node (we'll call it node X), timeout, then move on to the next node. Since this connection timed out, the driver adds node X to the "blacklist". New connections will now know to bypass node X. After 5 seconds, the blacklist is cleared and new connections will attempt to connect to node X once again.

We don't have a specific recommendation for mongo.ping_interval, however the concepts behind it are good to know if you're using the driver in production.

You're all set!

We hope this post helps you make the most out of the PHP driver. If you have any tips and tricks that you'd like to share please post in comments or write to us at so we can pass on the knowledge. Happy hacking!

28 Responses to MongoDB driver tips & tricks: PHP

  1. Themesrefinery 2014/07/11 at 3:33 am #

    Such a nice info.Great work.
    Rehman Ali

  2. adrian gutowski 2016/03/30 at 3:30 am #

    My colleagues were searching for FINRA Form U4 last year and were told about a great service that has an online forms library . If people are requiring FINRA Form U4 too , here’s or

  3. Royal Kuenzi 2016/05/12 at 2:40 pm #

    Here is the MongoClient usage from the php manual. Note you are missing the second parameter. I’ve tested this both ways for connectTimeoutMS and $driver_options does not affect the timeout.

    public MongoClient::__construct ([ string $server = “mongodb://localhost:27017” [, array $options = array(“connect” => TRUE) [, array $driver_options ]]] )

  4. Cheap Jerseys From China 2017/03/18 at 2:23 pm #

    2.5. Your child also needs to understand your expectations for his or her routine and that it needs to be followed.Article From Article Directory DatabaseMachado Getting Stronger As Spring Camp Nears RealGM WiretapWhen Orioles position players report to camp, third baseman Manny Machado, recovering from surgery on his left knee, will be there, but he doesn’t have a target date for his return. Should Bryant stay out of trouble, he could do well in the Cowboys offense with Miles Austin across the field.
    Cheap Jerseys From China

  5. cartier anello diamanti neri falso 2017/03/21 at 6:47 pm #

    cartierlovejesduas sounds like someone needs a good fuck
    cartier anello diamanti neri falso

  6. bracelet van cleef alhambra replique 2017/03/21 at 6:48 pm #

    cartierlovejesduas Yo supongo que el tema sonido era más una cuestión de la sala. Pero bueno, estuvo bien de verdad.
    bracelet van cleef alhambra replique

  7. bracelet cartier occasion replique 2017/03/21 at 6:50 pm #

    cartierlovejesduas Eu adoro cenoura, como crua às vezes, mas me causa prisão de ventre… 🙁
    bracelet cartier occasion replique

  8. is motor club america scam 2017/04/01 at 10:46 am #

    570985 187666Soon after I initially commented I clicked the -Notify me when new feedback are added- checkbox and now each time a remark is added I get four emails with exactly the same comment. Is there any method you will be able to take away me from that service? Thanks! 196931

  9. 822536 941147We guarantee authentic brands avoiding inferior commercial imitations, or even dangerous counterfeits. 188987

  10. Best News Website in World 2017/04/06 at 10:45 pm #

    930484 80577Spot up for this write-up, I seriously believe this web site needs a whole lot a lot more consideration. Ill apt to be once a lot more to learn additional, appreciate your that information. 903010

  11. Best Best Online News in the World 2017/04/07 at 12:29 am #

    655128 429711I enjoy the beneficial details you supply within your articles. 62441

  12. wholesale mlb jerseys free shipping 2017/04/12 at 11:32 am #

    Hi there to all, how is everything, I think every one is getting more from
    this website, and your views are good in favor of new people.wholesale mlb jerseys free shipping

  13. Cheap Jerseys From China 2017/04/20 at 12:59 am #

    I will help you how to sell gold based on what my grandfather coached me. Fake tanning products make it easier for anyone to stay away from the ill effects of too much UV radiation. You only need to top them up to have your appliance working well again. Customer service is of utmost significance to us and we guarantee that we would not let you down and you’re sure to see your invitees having lots of fun at the celebration.Local Art, Childrens or History Museums – Children like to go to museums, especially if it means having fun.
    Cheap Jerseys From China

  14. Wholesale Jerseys China 2017/04/20 at 1:01 am #

    You have to manage your time as well as your circumstances. Find a reputable company and tak? y?ur f?r?t step to bec?m?ng slimmer ?nd healthier. Tanners of such kind contain bronzers that temporarily coat the skin, giving the impression that you had just spent several minutes in the sun.It is not difficult to locate the manufacturer because the appliance bears the address and the name of the company it came from. The appropriate repair for the boot styles may well very last your shoes’ lifetime comfortably.
    Wholesale Jerseys China

  15. Wholesale Jerseys From China 2017/04/21 at 8:42 am #

    com/.A design of musical gear personifying the Vienna Philharmonic Orchestra, as nicely as the text Wiener Philharmoniker (“Vienna Philharmonic”), can be noticed on the flip side of the coin.This fruit ??? e??n appeared on t?e v?r??us American TV shows where t?e presenters ???? ?ll g?v?n glowing reports.Some parts need to be replaced rather than repaired to get the appliance back in a working state.Being the symbolic representation with the high-class requirement for the fashion persons, UGGs have grown a lot more widely used usually.
    Wholesale Jerseys From China

  16. Cheap Jerseys Wholesale 2017/04/21 at 3:32 pm #

    He has a coupletools that are game changing. Here, any teacher that seems to be relaxed in their task is fired and more committed people employed. This is what causes the development of a deep color that resembles a suntan. Crime in society is also highly minimized. If you would like to find out more on Sun Laboratories Tan Overnight Self Tanning products, click this link to the main site now.

  17. Wholesale NFL Jerseys Discount 2017/04/21 at 4:05 pm #

    When ???king f?r a supplement th?t ?ontains genuine authentic African Mango t??n ?ou ?hou?d not risk ?our health buying a cheap supplement with fillers, inst??d ?ou m?? b? b?tt?r off paying ? l?tt?? bit more. Through it, the standards of many countries have improved. However, control does not necessarily mean overseeing each and every little detail. handled a case recently against Wells Fargo Home Mortgage, in its capacity as a mortgage servicer servicing a mortgage first belonging to GE Capital, and then later to Freddie Mac. You can search online for the product too.
    Wholesale NFL Jerseys Discount

  18. Cheap NFL Jerseys 2017/04/21 at 4:05 pm #

    It s really not an a few finances, as the health of the eyes plus your ability to see clearly can be on the line. Additionally, if you have too much time wasters in your life or your worker’s life, then cut them out, too. All your relatives would surely be in for a treat on that day! Author Resource:-Visit our site for more information: Cotton Candy Machine, Bouncy Castle, Bouncy Castle Rental. This happens when the street children who would have otherwise been idle in crime, get involved in the busy schedule of learning.James Malinchak, Featured on ABC’s Hit Tv Show Secret Millionaire, is considered by many people experts as the World’s #1 Big Money Speaker Coach and Trainer.
    Cheap NFL Jerseys

  19. Wholesale Jerseys 2017/04/21 at 11:55 pm #

    5 percent required us to threaten a lawsuit to get those final minor tasks done.UGG boots will certainly recuperate the authentic form since yo placed on them in an extended time.Other lawsuits and attorneys general have become aware of this growing problem.Ice skating and roller skating are great activities for both boys and girls. Find a reputable company and tak? y?ur f?r?t step to bec?m?ng slimmer ?nd healthier.
    Wholesale Jerseys

  20. Cheap Jerseys China 2017/04/22 at 7:23 am #

    Public school finance is an activity that is very important. We still have a great relationship with our addition builder and would happily recommend him to anyone looking for a great home-building experience.No matter what product you are selling, find out how much it is currently selling for.Part of the problem is that there is little regulation of the mortgage servicing industry and therefore there are significant abuses that go unchecked. Valentino Crawford of The Grow Rich Project will show you how.

  21. Cheap Jerseys 2017/04/22 at 8:13 am #

    Having high cholesterol is bad f?r ??ur cardiovascular system ?nd wi?l put ??u at ? higher risk ?f suffering from a heart attack or ? stroke. These tanners rely on what’s called dihydroxyacetone or DHA.Pack some of your favorite healthy snacks, grab a sweater and catch a fun flick.LIBRARY. Is this your situation? Then continue reading! Its here to help.
    Cheap Jerseys

  22. Cheap NFL Jerseys China Wholesale 2017/04/22 at 2:44 pm #

    C. A consultancyservice may advise on anything from space requirements, to how toprepare the team for the integration, and to avoid a learning curve thatcould slow production times. The mortgage servicers don?t have enough financial incentives to modify the mortgages as they only earn on average of ? to ? percent of the value of the loans they service.On the internet searching may be beneficial to manage these types of types of difficulties. For further details visit cjmackeypress.

  23. Wholesale Jerseys From China 2017/04/22 at 9:44 pm #

    The information in the article you’ve just read will help you build a solid business. Beforepurchasing used flexo equipment it is important to make sure that thefacility is equipped for housing these printing presses.As we learned with our addition and home build, the difference between a great building experience or a bad one can be addressed by doing some early research and setting clear expectations before the work begins. She has an advanced degree in engineering and over twenty years making technology decisions for fortune 500 companies.The larger the mortgage payment, the more the mortgage servicers earn, and they earn less if the loan is modified, which frequently involves lowering the interest rate or taking other steps to reduce monthly mortgage payments.

  24. Cheap China Jerseys 2017/04/22 at 10:55 pm #

    Sometimes it can be difficult to establish no matter if or not your teaching program is too strenuous for the cardiovascular system.If your child is over 3 years old, the movie theater can be a great treat.James Malinchak Don’t Sweat The Small Stuff Delegate ItJames Malinchak Don’t Sweat The Small Stuff Delegate ItSeptember 29, 2013 Author: Matthew Maxwell Posted in MarketingHaving been in business for myself for many years, I have come to understand that the most essential thing I have done for myself would be to delegate the small stuff. Normal gold bullion coins are South African Krugerrand also American Gold Eagle, but my popular is the Austrian Vienna Philharmonic. Allow someone else edit and publish the book.
    Cheap China Jerseys

  25. needs to be done 2017/04/23 at 12:53 am #

    Way cool! Some extremely valid points! I appreciate you writing this
    article and also the rest of the website is really

  26. Cheap Jerseys Wholesale 2017/04/23 at 6:35 am #

    However, due to finances which in most cases are not adequate, the services in these institutions may not be as good.Chart all of the exercises that you do on a spreadsheet, in the event you are browsing to maximize your outcomes. Mortgage servicing is all automated, and if you really want to wait on hold sometime, try calling your mortgage servicer to straighten out a problem. You have many shopping and service choices. Tanners of such kind contain bronzers that temporarily coat the skin, giving the impression that you had just spent several minutes in the sun.
    Cheap Jerseys Wholesale

  27. Wholesale NFL Jerseys USA 2017/04/23 at 6:42 am #

    DHA’s effect lasts for approximately a week, lightening gradually as the skin is exfoliated.UGG boots will certainly recuperate the authentic form since yo placed on them in an extended time. Find free articles in our dofollow article directory, get free website content and submit your own articles for free.IMAX theaters are in many cities across the US now and have great educational films for kids, not to mention the theaters are enormous and have incredible sound systems. Although, I am going to admit, I enjoy addressing the packages with a personal note before they go out because I would like to maintain that personal touch.
    Wholesale NFL Jerseys USA

  28. Cheap Jerseys 2017/04/23 at 12:30 pm #

    Young ladies virtually all goal the particular uggs whose height has ended knee and easily show merely a small reduce upper leg in addition to towards the reason for leg.As long as your child is capable of being quiet, this should be a mandatory experience for children as someday it might be a thing of the past.PARKS.Number of View :117Tips about downloading digimon masters hackStrevel Morr   Submitted 2014-01-08 10:16:13 These days, computer games, that are simply referred to as PC games, have increased greatly in popularity.FA MIL YFUN1.

Leave a Reply