How to update object in mongodb via php?

by aniya.jaskolski , in category: MySQL , 3 months ago

How to update object in mongodb via php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by domenico , 3 months ago

@aniya.jaskolski 

To update an object in MongoDB using PHP, you can use the updateOne() or updateMany() methods. Here is an example of how to update an object:

  1. First, establish a connection to MongoDB:
1
2
3
4
5
<?php

$mongoClient = new MongoDBClient('mongodb://localhost:27017');
$database = $mongoClient->myDatabase;
$collection = $database->myCollection;


  1. Update an object using updateOne() method:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<?php

$filter = ['_id' => new MongoDBBSONObjectID('5f1c4f68e74a6bb2b1f04e22')];
$update = ['$set' => ['name' => 'John Doe', 'age' => 30]];

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

if ($result->getModifiedCount() > 0) {
    echo 'Document updated successfully';
} else {
    echo 'Document not updated';
}


  1. Update multiple objects using updateMany() method:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<?php

$filter = ['age' => ['$lt' => 30]];
$update = ['$set' => ['status' => 'inactive']];

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

if ($result->getModifiedCount() > 0) {
    echo 'Documents updated successfully';
} else {
    echo 'Documents not updated';
}


These are basic examples of how to update objects in MongoDB using PHP. You can modify the filter and update parameters according to your specific requirements.

Related Threads:

How to update nested mongodb object?
How to update array inside object in mongodb?
How to update data in MongoDB using PHP?
How to update a whole document in mongodb using php?
How to view an object embedded with a document in mongodb?
How to find object inside object in mongodb?