Tag archive for: databases

Inserting a document into a collection in MongoDB with PHP

Assume that we have a MongoDB server installed as a windows service on the same machine as our web server. The server listens on port 33333.

We met a new friend, and we want to save some details about her. That night, before bidding farewell, she said: “Remember me, I am Mary Jane. You can write to me at mary.jane@gmail.com“.

Although that’s all we have about her, this is sufficient for us to insert a document about Mary into our MongoDB database.

Inserting documents into collections in MongoDB with PHP consists of the following steps:

  • Derive an instance of the MongoCollection class that represents the MongoDB collection to insert documents.
  • Define the document to insert.
  • Define additional options for the insert.
  • Execute the insert function of the MongoCollection instance.

Connecting to and disconnecting from a MongoDB server in PHP

The first step to manipulate data in the MongoDB ecosystem is to connect to a MongoDB server. In php, we can use the Mongo class to help us connect to one or more MongoDB servers.

For the purpose of this demonstration, let’s assume that we had installed a MongoDB server instance as a windows service which listens on port 12345. In addition, our PHP web server runs on the same machine as the MongoDB instance.

Installing MongoDB as a windows service

After using MongoDB for quite a while, I realised that I had been repeating the starting up of the MongoDB database daemon whenever I reboot my PC. Manually starting the MongoDB database daemon via my command prompt whenever I want to work on my projects is inefficient.

Hence making MongoDB run as a windows service automatically when my computer starts up is one way to avoid repeating myself. In this post, I document how I install my MongoDB database as a windows service.