MongoDB PHP - MongoDB

How to use MongoDB with PHP?

MongoDB PHP driver should be used to use MongoDB with PHP. Download the driver from the url Download PHP Driver. Make sure that you download the latest release of it. Now unzip the archive and put php_mongo.dll in your PHP extension directory ("ext" by default). Add below line to your php.ini file

Make a Connection and Select a Database

To make a connection, specify the database name. If the database doesn't exist, MongoDB will create it automatically.

Below is the code snippet to connect to the database

When the program is executed, it produces result

Create a Collection

Below is the code snippet to create a collection

When the program is executed, it produces below result

Insert a Document

To insert a document into MongoDB, insert() method is used.

Below is the code snippet to insert a document

When the program is executed, it produces below result

Find All Documents

To select all documents from the collection, find() method is used.

Below is the code snippet to select all documents

When the program is executed, it produces below result

Update a Document

update() method can be used to update a document.

In below example, we will update the title of inserted document to MongoDB Tutorial. Below is the code snippet to update a document

When the program is executed, it produces result

Delete a Document

remove() method can be used to delete a document.
In below example, we will remove the documents that have the title MongoDB Tutorial. Below is the code snippet to delete a document

When the program is executed, it will produce below result

In the above example, second parameter is boolean type and used for justOne field of remove() method.
Remaining MongoDB methods findOne(), save(), limit(), skip(), sort() etc. works same as explained above.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

MongoDB Topics