How to update data in MongoDB using PHP?

by elise_daugherty , in category: PHP Databases , 2 years ago

How to update data in MongoDB using PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by jasen_gottlieb , a year ago

@elise_daugherty 

To update data in MongoDB using PHP, you can use the updateOne() or updateMany() method of the MongoDBCollection class.


Here is an example code that updates a document in a MongoDB collection using PHP:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php

// connect to MongoDB
$mongoClient = new MongoDBClient("mongodb://localhost:27017");

// select a database and collection
$database = $mongoClient->my_database;
$collection = $database->my_collection;

// define the filter and update
$filter = ['_id' => new MongoDBBSONObjectID('document_id')];
$update = ['$set' => ['name' => 'new_name']];

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

// check if the update was successful
if ($result->getModifiedCount() > 0) {
    echo "Document updated successfully.";
} else {
    echo "No document found matching the filter.";
}
?>


In this example, we first connect to a MongoDB instance using the MongoDBClient class. Then we select a database and a collection using the corresponding methods of the MongoDBClient class.


Next, we define the filter and update using the MongoDB query language. In this case, we are updating a document with a specific _id value and setting the name field to a new value.


Finally, we call the updateOne() method of the MongoDBCollection class to update the document. We check the result of the update using the getModifiedCount() method of the MongoDBUpdateResult class, which returns the number of documents that were modified.