How to Insert MongoDB Document using PHP

Introduction

To take advantage of everything MongoDB database has to offer in ways of database management, you’ll need to know how to correctly insert documents into your MongoDB collections. Since documents are stored as JavaScript Object Notation (JSON) and in BSON format, your’re actually making them super easy to retrieve when you use PHP to add them to a MongoDB database. Well, it’s a fact that the PHP code library is extensive and database coding is at its core. So without further delay, let’s proceed with this tutorial which explains how to insert MongoDB document using PHP.

Prerequisites:

  • MongoDB – Install the server and start it up.

  • MongoDB PHP Driver – Match the driver with your stable MongoDB version.

  • Check your driver. Make sure it’s correctly installed with the pcel command:

pecl search mongo
  • below is the result
Package Stable/(Latest) Local

mongo 1.6.16 (stable) MongoDB database driver

mongodb 1.6.0alpha1 (alpha) 1.5.3 MongoDB driver for PHP
  • To check what PHP version is installed in your system use below command:
php --version
  • The terminal should look similar to this:
PHP 7.2.15-0ubuntu0.18.04.2 (cli) (built: Mar 22 2019 17:05:14) ( NTS )

Copyright (c) 1997-2018 The PHP Group

Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies

with Zend OPcache v7.2.15-0ubuntu0.18.04.2, Copyright (c) 1999-2018, by Zend Technologies
  • Here’s a quick reference guide to determine the compatibility between MongoDB versions and drivers.

table mongodb php driver

MongoDB Daemon: Start it Up

  • Press Ctrl+Alt+T to open a terminal window for this instance.

  • These sudo commands give the appropriate access permissions, start up the MongoDB service, and verify its status:

sudo systemctl start mongod

sudo systemctl status mongod
  • Look for the “active (running)” status next to “Active” label to determine that everything is working properly. Your screen should closely resemble one like this:

running mongodb daemon

Use PHP to Insert a MongoDB Document

  • Create a testCollection sample collection and a testDatabase. Let’s put a test document into the that database. The MongoDBDriverBulkWrite; function collects and writes the actions to be executed byexecuteBulkWrite`.

>NOTE: Later in the script, we see $bulk->insert($doc); to insert the document, and $insertOneResult = $collection->insertOne() function lists the specifics of the document to insert.

// Using MongoDB\Driver\Manager

$bulk = new MongoDB\Driver\BulkWrite;

$doc = [

'clientName' => 'Raizel',

'email' => 'raizel@whatever.com',

'tag' => 'Admin User',

];

$bulk->insert($doc);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');

$result = $manager->executeBulkWrite('db.collection', $bulk);

// Using PHP Library

$collection = (new MongoDB\Client)->testDatabase->testCollection;

$insertOneResult = $collection->insertOne([

'clientName' => 'Raizel',

'email' => 'raizel@whatever.com',

'tag' => 'Admin User',

]);

Use PHP to Insert Multiple Documents in MongoDB

  • Create a theCollection collection and a theDatabase test database. Let’s insert multiple documents into that database.

>NOTE: Just like you insert MongoDB document using PHP, a single one, we use the MongoDB\Driver\BulkWrite; and executeBulkWrite functions to write and execute the operation. Documents to be inserted are listed. The second half of the script contains something different than the singular insertion method: The $insManyResult = $collection->insertMany() function to add multiple documents to the MongoDB database.

// Using MongoDB\Driver\Manager

$bulk = new MongoDB\Driver\BulkWrite;

$doc1 = ([

'movie_name' => 'Casper',

'genre' => 'comedy',

'language' => 'English',

]);

$doc2 = ([

'movie_name' => 'Eon Flux',

'genre' => 'action',

'language' => 'Korean',

]);

$bulk->insert($doc);

$bulk->insert($doc1);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');

$result = $manager->executeBulkWrite('db.collection', $bulk);

// Using PHP Library

$collection = (new MongoDB\Client)->theDatabase->theCollection;

$insManyResult = $collection->insertMany([

[

'movie_name' => 'Casper',

'genre' => 'comedy',

'language' => 'English',

],

[

'movie_name' => 'Eon Flux',

'genre' => 'action',

'language' => 'Korean',

],

]);

Conclusion

In this tutorial, you learned how to insert MongoDB document using PHP into a MongoDB database that is within a collection. As a bonus, to save more productivity, you also found out how to include multiple documents in a collection. Populating your MongoDB database is one of the main functions of managing it. When you couple that with PHP’s extensive open script capabilities, you’ve got a powerful team at your fingertips—of which you’re in full control.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed Redis,
MongoDB & Elasticsearch

Get Started

OR

Try CockroachDB
in Beta

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.