Table of Content
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' => 'john.doe@example.com',
'age' => 30,
'registered_at' => new MongoDB\BSON\UTCDateTime() // Current timestamp
];
$result = $collection->insertOne($document);
echo "Inserted document with ID: " . $result->getInsertedId();
- The
insertOnemethod 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' => 'alice.smith@example.com',
'age' => 25,
],
[
'name' => 'Bob Brown',
'email' => 'bob.brown@example.com',
'age' => 35,
]
];
$result = $collection->insertMany($documents);
echo "Inserted " . $result->getInsertedCount() . " documents.";
- The
insertManymethod takes an array of documents, allowing you to batch-insert data efficiently. - Each document automatically gets a
unique _idfield 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' => 'validated.user@example.com',
'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' => 'new.user@example.com',
'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_hashfunction ensures passwords are stored securely, following best practices. - Timestamps: The
created_atfield captures when the user was registered, using MongoDB’sUTCDateTimefor precision. - Error Handling: The
try-catchblock 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
In PHP, manipulation of XML data can be very critical when most systems' data exchange relies on the format. XML—Extensible…
The array_column function in PHP takes values from one column in a multidimensional array. You can use it to pull…
In this article, You will understand everything you need to know about how to use PHP to select data from…
Arrow functions were introduced in PHP 7.4. They offer you a way to write simple operations, such as calculations, filters,…
Think about the PHP variable as little storage boxes holding your data, whether it is a number, a word, or…
File Handling in PHP is an important tool especially when you need to manage files such as reading, writing, or…
In some cases, you need to handle a lot of data or simply try to open a file, or read…
A destructor in a PHP class runs when an object is no longer needed. It frees resources and cleans up…
Abstract class in PHP appeared to provide a way to define a structure for related classes and don't allow direct…
Variables in PHP are general elements used for data storage and other manipulations. Global variables belong to a particular category…