Learn How to Insert Documents in MongoDB Using PHP

Inserting documents into your MongoDB collections is one of the most basic but important tasks when working with PHP. In this guide, I will take you through each step of the process so that everything is clear and easy to follow.

Inserting a Single Document

Adding a single document to your MongoDB collection is simple. Take a look at this example:

$document = [
    'name' => 'John Doe',
    'email' => '[email protected]',
    'age' => 30,
    'registered_at' => new MongoDB\BSON\UTCDateTime() // Current timestamp
];

$result = $collection->insertOne($document);

echo "Inserted document with ID: " . $result->getInsertedId();
  • The insertOne method is your go-to for inserting a single document.
  • MongoDB automatically generates the _id field if you do not specify it yourself.

You can quickly add individual entries to your database while letting MongoDB handle key details like unique IDs.

let’s move on to the following section to learn how to insert multiple records.

insert multiple records

When you need to add multiple documents to your MongoDB collection at once, the insertMany method makes it a breeze. Here is how it works:

$documents = [
    [
        'name' => 'Alice Smith',
        'email' => '[email protected]',
        'age' => 25,
    ],
    [
        'name' => 'Bob Brown',
        'email' => '[email protected]',
        'age' => 35,
    ]
];

$result = $collection->insertMany($documents);

echo "Inserted " . $result->getInsertedCount() . " documents.";
  • The insertMany method takes an array of documents, allowing you to batch-insert data efficiently.
  • Each document automatically gets a unique _id field unless you explicitly define one.

In the following section, you will learn how to validate user data before inserting it into the database.

Validating Data Before Insertion

Before inserting documents, validating your data ensures consistent and reliable database entries. You can perform checks like:

  • Required Fields: Ensure necessary fields are present.
  • Data Types: Validate types (e.g., integers, strings, or arrays).

Example validation:

$document = [
    'name' => 'Validated User',
    'email' => '[email protected]',
    'age' => 'not_a_number'
];

if (!is_numeric($document['age'])) {
    echo "Error: 'age' must be a number.";
    exit;
}

$collection->insertOne($document);

Let’s move on to the section below, to see an example.

Example

Consider you are building a user registration system. Here is how you can securely store user data in your MongoDB collection:

$document = [
    'username' => 'new_user',
    'password' => password_hash('securepassword', PASSWORD_DEFAULT), // Securely hash the password
    'email' => '[email protected]',
    'created_at' => new MongoDB\BSON\UTCDateTime() // Current timestamp
];

try {
    $collection->insertOne($document);
    echo "User registered successfully!";
} catch (MongoDB\Driver\Exception\Exception $e) {
    echo "Error: " . $e->getMessage();
}
  • Secure Passwords: The password_hash function ensures passwords are stored securely, following best practices.
  • Timestamps: The created_at field captures when the user was registered, using MongoDB’s UTCDateTime for precision.
  • Error Handling: The try-catch block gracefully handles any database errors, ensuring your application can respond appropriately.

You can create a robust user registration system that safely stores and validates critical user data.

Let’s summarize it 

Wrapping Up

Inserting documents into MongoDB using PHP is an important task for developers working with this database. So if you are adding a single document, managing bulk operations, or focusing on performance, PHP gives you the tools to handle it. 

    Similar Reads

    PHP Object | How to Create an Instance of a Class

    The PHP object is an instance from the PHP class or the main data structure that is already been created…

    PHP Singleton Pattern: How to Use with Examples

    The PHP singleton design pattern makes sure that the class has only one instance and provides a global access point…

    PHP File Inclusion: require, include, require_once, include_once

    PHP offers four main functions to include files: require, require_once, include, and include_once. Each one gives you a similar purpose…

    PHP filter_id Function: How to Retrieve PHP Filter IDs

    Before PHP 5.2, there was no built-in filter extension in PHP. You had to manually handle and sanitize input. PHP…

    PHP Array Operators: Union, Equality, Identity

    PHP arrays serve as powerful tools for storing multiple values in a single variable. To manipulate arrays efficiently, PHP provides…

    PHP Data Types: Understanding the 10 Primitive Types

    The whole world of PHP programming revolves around data, be it numbers, text, or more complicated structures. Each of these…

    PHP Switch | How the Switch Statement Works in PHP

    The PHP switch statement is multiple conditions to only execute one block if its condition generating a true boolean value.…

    PHP strtoupper Function: Convert Strings to Uppercase

    Use strtoupper() function when you want to change all letters in a string to uppercase in PHP. It works with…

    PHP range Function: Create Arrays with Sequence Values

    The PHP range function helps you make sequences. Without it, you would write loops every time you need numbers or…

    PHP str_replace Function: How it Works with Examples

    If you find a word that does not fit and want to fix it. You can use the PHP str_replace…

    Previous Article

    MongoDB CRUD with PHP: Create, Read, Update, and Delete

    Next Article

    Find Documents in MongoDB Using PHP

    Write a Comment

    Leave a Comment

    Your email address will not be published. Required fields are marked *


    Subscribe to Get Updates

    Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
    No spam. Unsubscribe anytime.