What is MongoDB?

In this article we are going to show you the basics of MongoDB, but first, what is MongoDB? Is a cross-platform document oriented and NoSQL database.

What does it mean?

MongoDB doesn’t implement the tranditional relational database structure, instead it uses a structure similar to JSON documents with dynamic schemas.

What is needed to connect to a MongoDB database from PHP?

  • A MongoDB database running.
  • The PHP Driver installed.

To install the PHP Driver:

If you want to install MongoDB for local development then I recommend  AMPPS as one of the easiest way to get your LAMP stack , which also includes MongoDB. http://ampps.com/downloads

Connecting to MongoDB from PHP

 

Selecting the database instance:

Note: No strings/quotes (“) needed around your database name.

How to create a collection? (what you know as tables in traditional relational databases)

Selecting the collection you are going to work with

Note: No strings/quotes (“) needed around your collection name.

How to insert a document? (what you know as record in  traditional relational databases)

First we create an array.

Let’s say we want to insert a document with 2 columns, then:

Then we insert it by doing:

*Is important to mention that MongoDB is Schemaless therefor we can have many documents with varying set of fields and with different types. Example:

And then we could have another document with:

*MongoDB by default create an ID for each document. This id is defined as _id in each document.

How to find a document?

If you want to get all documents inside a collection then:

Let say we want to print all the name, then we loop by each one:

To get a specific document:

We can also specify which columns we want in the results by adding another array with the name of the columns. Example:

Now the results will include the _id , name and company columns.

If we want to search by using the _id column then:

How to update a document?

We first find the document we want to update.

Then we can directly change the values in the result array, like this:

Finally, commit the changes:

Deleting a document from the collection

In this article we have showed the basics of using MongoDB. If you liked this article, make sure you hit that share button. Subscribe and stay tune for more MongoDB.

Subscribe To Our Newsletter

Join our mailing list to receive the latest news and updates from our team.

You have Successfully Subscribed!

Share This