How to Update Documents in MongoDB Using PHP

Updating documents in MongoDB with PHP involves using the updateOne or updateMany methods from the MongoDB PHP library. These methods allow for precise updates, whether targeting a single document or multiple ones.

Updating a Single Document

The updateOne method is ideal for updating a single document. Specify a filter to identify the document and an update array to define changes.

$filter = ['username' => 'john_doe'];
$update = ['$set' => ['email' => 'john.doe@example.com']];

$result = $collection->updateOne($filter, $update);

echo $result->getModifiedCount() . " document updated.";

The filter targets documents with a specific username, and the $set operator modifies the email field.

Let’s move on to the following section on how to update multiple documents at once.

Updating Multiple Documents

When multiple documents need updates, use updateMany. This method applies changes to all matching documents.

$filter = ['status' => 'inactive'];
$update = ['$set' => ['status' => 'active']];

$result = $collection->updateMany($filter, $update);

echo $result->getModifiedCount() . " documents updated.";

This example updates the status field for all documents marked as inactive. Let’s see how we can do that using additional operators in the section below.

Using Additional Update Operators

MongoDB supports various update operators, such as $inc, $push, and $unset. These operators enable advanced update operations.

Incrementing a value

$filter = ['views' => ['$exists' => true]];
$update = ['$inc' => ['views' => 1]];

$result = $collection->updateOne($filter, $update);
echo $result->getModifiedCount() . " document updated.";

It increments the views field for a document in a MongoDB collection. The $filter checks if the views field exists using the $exists operator. The $update uses the $inc operator to increase the views value by 1. The updateOne method applies the update to the first matching document, and the getModifiedCount() method returns the number of documents modified, which is then displayed.

Adding elements to an array

$filter = ['username' => 'john_doe'];
$update = ['$push' => ['tags' => 'new_tag']];

$result = $collection->updateOne($filter, $update);
echo $result->getModifiedCount() . " document updated.";

It adds a new value to the tags array field in a MongoDB document. The $filter targets a document where the username is john_doe. The $update uses the $push operator to append 'new_tag' to the tags array. The updateOne method applies the update to the first matching document, and the getModifiedCount() method outputs the number of documents modified.

Let’s summarize it.

Wrapping Up

Updating documents in MongoDB allows you to modify data in a simple way, So if you need to adjust single fields or update multiple records at once. It is an important for managing dynamic databases.

Here is a quick recap of what we covered:

  • Updating a single document: Using updateOne with a filter and update array to target and modify specific fields.
  • Updating multiple documents: Using updateMany to apply changes to all matching documents.
  • Using additional operators: Employing $inc, $push, and other operators for advanced update operations.

    Similar Reads

    PHP Callable & Callback: Pass a Function to Another

    The callback in PHP lets you pass functions as arguments and reuse code. It helps you to control how tasks…

    Abstract Class in PHP: How It Works & Examples

    Abstract class in PHP appeared to provide a way to define a structure for related classes and don't allow direct…

    PHP array_rand() Function: Usage & Examples

    The array_rand() is a helper function in PHP that makes it easier when dealing with arrays; you can just pull…

    PHP $GLOBALS: Access Global Variables with Examples

    When you start working with PHP, you’ll soon need access to variables from multiple places in your code. For this,…

    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 fclose(): Close Access of File Manipulation

    Actually, PHP has a built-in function that doesn’t get the spotlight—fclose(). It ends the file manipulation code. Let’s break down…

    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 array_intersect_assoc: How it Works with Examples

    PHP array_intersect_assoc compares values and keys in arrays. It returns matches with the same key and value from all arrays…

    PHP array_diff_key Function: How it Works with Examples

    PHP array_diff_key compares arrays and removes elements that share the same key. It checks only keys and keeps the values…

    PHP is_readable: Check File Accessibility

    The PHP is_readable helps you validate file readability before any operation like read or include files. What Is PHP is_readable? The is_readable() function…

    Previous Article

    Find Documents in MongoDB Using PHP

    Next Article

    How to Delete Documents in MongoDB with 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.