Php Mongodb bulk write example - php

I am using PHP, CodeIgniter4 and Mongo DB.
I got lot of example of connecting mongodb and php
I installed mongo db
After that for driver -> sudo pecl install mongodb
And Next -> composer require mongodb/mongodb
I am able to do curd opertaion.
Using below code
$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->demo->beers;
$result = $collection->insertOne( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );
echo "Inserted with Object ID '{$result->getInsertedId()}'";
Same for update delete and find got reference from https://www.php.net/manual/en/mongodb.tutorial.library.php
Kind of Stuck doing bulkWrite.
$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->insert(['_id' => 1, 'x' => 1]);
$bulk->insert(['_id' => 2, 'x' => 2]);
$bulk->update(['x' => 2], ['$set' => ['x' => 1]]);
$bulk->insert(['_id' => 3, 'x' => 3]);
$bulk->delete(['x' => 1]);
I got this reference from https://www.php.net/manual/en/class.mongodb-driver-bulkwrite.php
But I am getting an error saying MongoDB\Driver\BulkWrite not found.
and I am not getting any relevant example MongoDB\Client .

Related

Try to execute query in MongoDB using PHP

I just trying to config the PHP access to my MongoDB database. First of all, the MongoDB driver was installed in the PHP and it was update the php.ini. The code below works without any warning or error and apparently everything is just fine:
$options = [
'username' => 'user',
'password' => '123456',
'authSource' => 'database',
];
$mongo = new MongoDB\Driver\Manager('mongodb://localhost:27017', $options);
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$document = array("key" => "value", "another_key" => "another_value"); //...and so on...
$bulk->insert($document);
$result = $mongo->executeBulkWrite('db.mycollection', $bulk, $writeConcern);
But, when I check my database, nothing happened: no document were inserted!!!
What I'm doing wrong???

Laravel mongodb transactions

I need to use transactions on MongoDB in Laravel.
I downloaded the php MongoDB driver 1.6 and copied and pasted php_mongodb.dll into the php/ext folder.
I also installed the php mongo library through
composer require mongodb/mongodb
Now, when I try to use transactions according to this, it doesn't rollback when an error occurs.
$client = new Client($url);
$callback = function (\MongoDB\Driver\Session $session) use ($client) {
$data = [
"name" => "Tommy",
];
$collection = $client->db1->users;
$user = $collection->updateOne(
['mobile' => '*'],
['$set' => $data],
[$session]
);
$data = [
"activate" => 1,
];
$collection = $client->db1->wallets;
$wallet1 = $collection->updateOne(
['_id' => 100],
['set' => $data],
[$session]
);
};
$session = $client->startSession();
$transactionOptions = [
'readConcern' => new \MongoDB\Driver\ReadConcern(\MongoDB\Driver\ReadConcern::LOCAL),
'writeConcern' => new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000),
'readPreference' => new \MongoDB\Driver\ReadPreference(\MongoDB\Driver\ReadPreference::RP_PRIMARY),
];
try{
\MongoDB\with_transaction($session, $callback, $transactionOptions);
return true;
}catch (\Exception $e)
{
return false;
}
The session class in MongoDB\Driver\Session is unknown in laravel while this class is for mongodb>=1.4.0. I don't know what is wrong. Can anyone help me?

"Class 'MongoDB\Driver\Manager' not found" in PHP

I installed MongoDB library with Composer:
composer require jenssegers/mongodb
I got that error: "Class 'MongoDB\Driver\Manager' not found",
I tried many things but problem is not solved,
But finally I noticed that the class file is really not existing in library!
I havent found it anyway...
What am I missing?
Where can I found full package for MongoDB in PHP?
Please be aware of that: similar questions are not mentioning lack of class file.
Usually your code should contain a link to 'vendor/autoload.php' with the correct path to it similar to the following:
$DB_CONNECTION_STRING="mongodb://YourCredentials";
require '../../vendor/autoload.php';
Then if you use MongoDB\Driver\Manager, a modern version of MongoDB driver, you have something such as these CRUD operations in your code:
Create a document in the collection:
$bulkWrite = new MongoDB\Driver\BulkWrite;
$doc=['name' => 'John', age => 33, profession => 'Guess what?'];
$bulk->insert($doc);
$mongoConn->executeBulkWrite('db.col', $bulkWrite);
Read document in the collection by name with a limit:
$filter = ['name' => 'John'];
$options = ['limit' => 2];
$query = new MongoDB\Driver\Query($filter, $options);
$mongoConn->executeQuery('db.MyCollection', $query);
Read document in the collection by MongoDb _id with a limit:
$filter = ['_id' => new MongoDB\BSON\ObjectID( '5bdf54e6d722dc000f0aa6c2' )];
$options = ['limit' => 2];
$query = new MongoDB\Driver\Query($filter, $options);
$mongoConn->executeQuery('db.MyCollection', $query);
Update document in the collection:
$bulkWrite = new MongoDB\Driver\BulkWrite;
$filter = [];
$update = ['$set' => array()];
$options = ['multi' => false, 'upsert' => false];
$bulkWrite->update($filter, $update, $options);
$mongoConn->executeBulkWrite('db.MyCollection', $bulkWrite);
Delete document in the collection - Delete:
$bulkWrite = new MongoDB\Driver\BulkWrite;
$filter = ['name' => 'John', age => 33];
$options = ['limit' => 1];
$bulkWrite->delete($filter, $options);
$mongoConn->executeBulkWrite('db.col', $bulkWrite);

MongoClient Class vs. MongoDB\Driver\Manager Class

I want to get your recommend about my web project. I use PHP and MongoDB but I was confused when I read this sentence from php documentation.
This extension that defines this class is deprecated. Instead, the MongoDB extension should be used. Alternatives to this class include:
MongoDB\Driver\Manager
I already used MongoClient Class for CRUD but after reading that sentence, I tried to migrate MongoClient to MongoDB\Driver\Manager. The connection using MongoDB\Driver\Manager was successed but I couldn't anymore :(
My PHP version is 5.6.29.
Mongo extension version is 1.7.0
MongoDB extension version is 1.2.9
My questions are:
Do I have to use MongoDB\Driver\Manager Class?
Is it better than MongoClient Class?
Here is a good answer about deprecated language features:
What does PHP do with deprecated functions?
And here is a proper usage for php with mongodb:
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$filter = [];
$options = [
'sort' => ['_id' => 1],
];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery('db.collection', $query);
foreach ($cursor as $document) {
//...
}
There are are a lot of tutorials for CRUD operation with php and mongodb, for example: MongoDB PHP tutorial
In short: you should not use deprecated feature because of security reasons and because it could get removed from php in the future. So better update your code.
I personally came across with the absence of a link to 'vendor/autoload.php'. It started working after my code looked like the following:
$DB_CONNECTION_STRING="mongodb://YourCredentials";
require '../vendor/autoload.php';
$manager = new MongoDB\Driver\Manager( $DB_CONNECTION_STRING );
Then if you use MongoDB\Driver\Manager, a modern version of MongoDB driver, you implement CRUD operations such as the following:
Create a document in the collection:
$bulkWrite = new MongoDB\Driver\BulkWrite;
$doc = ['name' => 'John', age => 33, profession => 'Guess what?'];
$bulkWrite->insert($doc);
$manager->executeBulkWrite('db.MyCollection', $bulkWrite);
Read document in the collection by name with a limit:
$filter = ['name' => 'John'];
$options = ['limit' => 2];
$query = new MongoDB\Driver\Query($filter, $options);
$manager->executeQuery('db.MyCollection', $query);
Read document in the collection by MongoDb _id with a limit:
$filter = ['_id' => new MongoDB\BSON\ObjectID( '5bdf54e6d722dc000f0aa6c2' )];
$options = ['limit' => 2];
$query = new MongoDB\Driver\Query($filter, $options);
$manager->executeQuery('db.MyCollection', $query);
Update document in the collection: (Read more about options upsert and multi here)
$bulkWrite = new MongoDB\Driver\BulkWrite;
$filter = ['name' => 'John'];
$update = ['$set' => ['name' => 'Smith', age: 35, profession => 'Guess what?']];
$options = ['multi' => false, 'upsert' => false];
$bulkWrite->update($filter, $update, $options);
$manager->executeBulkWrite('db.MyCollection', $bulkWrite);
Delete document in the collection - Delete:
$bulkWrite = new MongoDB\Driver\BulkWrite;
$filter = ['name' => 'John', age => 35];
$options = ['limit' => 1];
$bulkWrite->delete($filter, $options);
$manager->executeBulkWrite('db.MyCollection', $bulkWrite);

Php MongoDB, Fatal error: Class 'MongoDB\Driver\Manager' not found in

image for mongo info
MongoDB shell version v3.4.1
mongodb driver v1.6.14
xampp v3.2.1, Apache/2.4.16 (Win32) OpenSSL/1.0.1p PHP/5.6.12
i m running for first time and getting this problem plz help me.
Fatal error: Class 'MongoDB\Driver\Manager' not found in H:\xampp\htdocs\www\phpmongodb\vendor\mongodb\mongodb\src\Client.php on line 81
I had the same error before I set up the mongodb added the following link to 'vendor/autoload.php'. In many cases you need to check your hosting. It started working after my code looked like the following:
$DB_CONNECTION_STRING="mongodb://YourCredentials";
require '../../vendor/autoload.php';
$manager = new MongoDB\Driver\Manager( $DB_CONNECTION_STRING );
Then if you use MongoDB\Driver\Manager, a modern version of MongoDB driver, you have something looks such as this:
Create a document in the collection:
$bulkWrite = new MongoDB\Driver\BulkWrite;
$doc = ['name' => 'John', age => 33, profession => 'Guess what?'];
$bulkWrite->insert($doc);
$manager->executeBulkWrite('db.MyCollection', $bulkWrite);
Read document in the collection by name with a limit:
$filter = ['name' => 'John'];
$options = ['limit' => 2];
$query = new MongoDB\Driver\Query($filter, $options);
$manager->executeQuery('db.MyCollection', $query);
Read document in the collection by MongoDb _id with a limit:
$filter = ['_id' => new MongoDB\BSON\ObjectID( '5bdf54e6d722dc000f0aa6c2' )];
$options = ['limit' => 2];
$query = new MongoDB\Driver\Query($filter, $options);
$manager->executeQuery('db.MyCollection', $query);
Update document in the collection: (Read more about options upsert and multi here)
$bulkWrite = new MongoDB\Driver\BulkWrite;
$filter = ['name' => 'John'];
$update = ['$set' => ['name' => 'Smith', age: 35, profession => 'Guess what?']];
$options = ['multi' => false, 'upsert' => false];
$bulkWrite->update($filter, $update, $options);
$manager->executeBulkWrite('db.MyCollection', $bulkWrite);
Delete document in the collection - Delete:
$bulkWrite = new MongoDB\Driver\BulkWrite;
$filter = ['name' => 'John', age => 35];
$options = ['limit' => 1];
$bulkWrite->delete($filter, $options);
$manager->executeBulkWrite('db.MyCollection', $bulkWrite);

Categories