Call to undefined method MongoDB::update() - php

when using the update statement via PHP means am getting the error.
Call to undefined method MongoDB::update()
I'm using the mongo-php-driver driver for connecting the MongoDB and PHP
My Code
$result = $this->mongo_db->update('table_name',array('user_type'=>"D"),array('$set'=>array('account_balance'=>0)),array('upsert'=>true));
My MongoDB reference link is https://docs.mongodb.com/manual/reference/method/db.collection.update/

Hi am using updateMany instead of update. Its working fine for me.
$result = $this->mongo_db->updateMany('table_name',array('user_type'=>"D"),array('$set'=>array('account_balance'=>0)),array('upsert'=>true));

From the documentation
Use the MongoDB\Collection::updateOne() method to update a single document matching a filter. MongoDB\Collection::updateOne() returns a MongoDB\UpdateResult object, which you can use to access statistics about the update operation.
<?php
$collection = (new MongoDB\Client)->test->users;
$collection->drop();
$collection->insertOne(['name' => 'Bob', 'state' => 'ny']);
$collection->insertOne(['name' => 'Alice', 'state' => 'ny']);
$updateResult = $collection->updateOne(
['state' => 'ny'],
['$set' => ['country' => 'us']]
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
For Extra Read:
The MongoDB PHP Library and underlying mongodb extension have notable API differences from the legacy mongo extension. Please read the upgrade guide for more details.

You should check if the mongo db extension is installed and available. Install it with pecl:
https://stackoverflow.com/a/74844843/2862728

Related

Transaction in MongoDB 4.2 with new PHP Driver

I am new to MongoDB as I was a SuperFan of MySQL before. I recently moved to this NoSQL thing and loved it but now I am badly trapped at Transactions in MongoDB.
I found some related questions on SO but with no answers or obsolete which does not work with new MongoDB PHP Driver as there are many changes in syntax/functions and I could see many newbie like me are confused between MongoDB Docs and PHP Driver.
I found this way of committing transactions in MongoDB Docs
$client = new MongoDB\Driver\Manager("mongodb://127.0.0.1:27017");
$callback = function (\MongoDB\Driver\Session $session) use ($client)
{
$client->selectCollection('mydb1', 'foo')->insertOne(['abc' => 1], ['session' => $session]);
$client->selectCollection('mydb2', 'bar')->insertOne(['xyz' => 999], ['session' => $session]);
};
// Step 2: Start a client session.
$session = $client->startSession();
// Step 3: Use with_transaction to start a transaction, execute the callback, and commit
$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),
];
\MongoDB\with_transaction($session, $callback, $transactionOptions);
but this syntax/functions are obsolete for new PHP Driver and it gives following error
Call to undefined function MongoDB\with_transaction()
According to PHP Docs, the new PHP Driver for MongoDB provides these options to commit transaction but I don't understand how? because there is no example given in docs.
https://www.php.net/manual/en/mongodb-driver-manager.startsession.php
https://www.php.net/manual/en/mongodb-driver-session.starttransaction.php
https://www.php.net/manual/en/mongodb-driver-session.committransaction.php
My Question is, How can I update the above code with New PHP Driver's functions? I believe to use
MongoDB\Driver\Manager::startSession
MongoDB\Driver\Session::startTransaction
MongoDB\Driver\Session::commitTransaction
but I don't understand what their syntax is or their arguments etc because of incomplete documentation and no examples. Thanking you in anticipation for your time and support.
Ok, So, I found the answer to my question and I thought it can be helpful for some others
using Core Mongo Extension
$connection = new MongoDB\Driver\Manager("mongodb://127.0.0.1:27017");
$session = $connection->startSession();
$session->startTransaction();
$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->insert(['x' => 1]);
$bulk->insert(['x' => 2]);
$bulk->insert(['x' => 3]);
$result = $connection->executeBulkWrite('db.users', $bulk, ['session' => $session]);
$session->commitTransaction();
using PHP Library
$session = $client->startSession();
$session->startTransaction();
try {
// Perform actions.
//insertOne(['abc' => 1], ['session' => $session]); <- Note Session
$session->commitTransaction();
} catch(Exception $e) {
$session->abortTransaction();
}
Note: To make the answer short and to the point, I have omitted some of the optional parameters and used a dummy insert data etc without any try-catch.
If you are running MongoDB instance as standalone version that is for development or testing purpose then you might get error something like
transaction numbers are only allowed on a replica set member or mongos
Then you can enable Replica on a standalone instance following this guide https://docs.mongodb.com/manual/tutorial/convert-standalone-to-replica-set/

How can I integrate elasticsearch to mysql using php

I was working on a project which is required to use elasticsearch. I followed the guide: https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/index.html
It works perfectly for me:
require 'vendor/autoload.php';
use Elasticsearch\ClientBuilder;
$hosts = [
'myhost'
];
$client = ClientBuilder::create() // Instantiate a new ClientBuilder
->setHosts($hosts) // Set the hosts
->build();
$params = [
'index' => 'php-demo-index',
'type' => 'doc',
'id' => 'my_id',
'body' => ['testField' => 'abc']
];
$response = $client->index($params);
print_r($response);
Now, that's only a basic thing. Now, what I want is to integrate this with Mysql i.e. as I update or insert into my table in database, it get indexed automatically in elasticsearch.
I know, we have Logstash that can query db constantly after a given interval and index into elasticsearch. But, I want indexing to be happened automatically after insertion into db using PHP without logstash.
I know such a library in (nodeJs+mongodb) ie. mongoosastics: https://www.npmjs.com/package/mongoosastic. Is there any library available in php which can do such a task automatically. Please provide me the sample code, if you know one.
There is indeed libraries to automate this task. However it generally requires the use of an ORM like Doctrine in order gracefully hook in to your database implementation. If you are able to use the Symfony framework in your project there is a library called FOSElasticaBundle which keeps your indices in sync with your database operations.

MapReduce with PHP and MongoDB

I'm fairly new to Mongo and I have what I thought was a simple question. How do I do MapReduce with PHP and the non legacy MongoDB driver http://php.net/manual/en/set.mongodb.php or the higher level package mongodb/mongodb found at https://packagist.org/packages/mongodb/mongodb?
Every example I've seen seems to use the legacy driver (http://php.net/manual/en/book.mongo.php). They all use the MongoCode object, which doesn't exist in mongodb.php. It exists in mongo.php (the legacy driver). When I try and use it, it will say that "Class 'MongoCode' not found".
My code looks something like:
$function = "function() { emit(this); }";
$map = new \MongoCode($function);
$command = $db->command([
"mapreduce" => "db.archiveData",
"map" => $map,
"query" => $query,
"out" => "data"
]);
To make things more confusing, when I look at the source at https://github.com/mongodb/mongo-php-library, there is a unit test for MapReduce (https://github.com/mongodb/mongo-php-library/blob/4dc36f6231df133a57ff0dc5a0123945133d25ba/tests/Operation/MapReduceFunctionalTest.php). But it uses the MongoDB\Operation\MapReduce, which doesn't seem to exist in the 1.1 version of mongodb/mongodb.
I thought maybe I would call it on the server using JavaScript. But when I look at http://php.net/manual/en/mongodb.execute.php, it says it "is deprecated in MongoDB 3.0+". So that doesn't feel like something I should use.
So is it that:
MapReduce is not supported with mongodb/mongodb. Or maybe it is not supported yet, but will be?
I have to use the legacy driver for MapReduce?
I have to figure out a way to call db.collection.mapReduce via JavaScript on the server?
I have to use the Aggregation Pipeline (https://docs.mongodb.com/manual/aggregation/) to do map reduce type of actions? But that feels much more limited.
What am I missing?
So I now have clarity on where things are at.
MapReduce will be officially supported in 1.2.0 of PHPLib (https://jira.mongodb.org/browse/PHPLIB-53)
Until then, there is a completely usable workaround by using the command object as per https://docs.mongodb.com/php-library/current/upgrade/#mapreduce-command-helper
Example is here as well:
$database = (new MongoDB\Client)->selectDatabase('db_name');
$cursor = $database->command([
'mapReduce' => 'collection_name',
'map' => new MongoDB\BSON\Javascript('...'),
'reduce' => new MongoDB\BSON\Javascript('...'),
'out' => 'output_collection_name',
]);
$resultDocument = $cursor->toArray()[0];
You can also use MapReduce via Doctrine (http://docs.doctrine-project.org/projects/doctrine-mongodb-odm/en/latest/reference/map-reduce.html), but that is using legacy and a shim. So probably not a good choice for a new project.

Use of undefined constant OAUTH_AUTH_TYPE_FORM - assumed 'OAUTH_AUTH_TYPE_FORM'

While using the upwork api library https://github.com/upwork/php-upwork, I got error
Use of undefined constant OAUTH_AUTH_TYPE_FORM - assumed 'OAUTH_AUTH_TYPE_FORM'.
I am using the OAuth1 - Authtype
here's the code I have written:
$config = new \Upwork\API\Config(
array('consumerKey' => 'MY_KEY',
'consumerSecret' => 'MY_SECRET',
'accessToken' => \Session::get('access_token'),
'accessSecret' => \Session::get('access_secret'),
'verifySsl' => false,
'debug' => false,
'authType' => 'OAuth1'
)
);
$client = new \Upwork\API\Client($config);
if (!empty(\Session::get('access_token')) && !empty(\Session::get('access_secret'))) {
$client->getServer()
->getInstance()
->addServerToken(
$config::get('consumerKey'),
'access',
\Session::get('access_token'),
\Session::get('access_secret'),
0
);
} else {
// $accessTokenInfo has the following structure
// array('access_token' => ..., 'access_secret' => ...);
// keeps the access token in a secure place
// gets info of authenticated user
$accessTokenInfo = $client->auth();
}
$auth = new \Upwork\API\Routers\Auth($client);
print_r($auth);
As per their readme:
[You need to have] OAuth Extension installed (optional), we recommend using official pecl extension, but in case you want to use your own library, you need to drop line 'ext-oauth' from composer json, or do not use composer, which is also optional. In that case, you need to setup the 'authType' parameter in your configuration options.
And:
IMPORTANT:
The library supports different OAuth clients, by default it requires PECL PHP extension
While they suggest it as optional, the OAUTH_AUTH_TYPE_FORM constant is part of the PECL extension.
I suggest to fix, you install the PHP OAuth extension.
FYI, http://php.net/manual/en/oauth.setauthtype.php - it's a constant from OAuth extension. Seems you didn't install it as recommended. Otherwise, use a separate library - see details in README.

Mongodb php7, Update document by id?

I moved from mongo to mongodb extension when I upgraded to PHP7. The only thing I cannot figure out is to update a doc by id. Mongo used to have the MongoId Class to parse the id from string but I can't find any equivalent for Mongodb.
This is where I'm at and which doesn't work
$collection->updateOne(['_id' => '567eba6ea0b67b21dc004687'], ['$set' => ['some_property' => 'some_value']]);
The _id should be a instance of BSON:
$collection->updateOne(['_id' => new \MongoDB\BSON\ObjectID('567eba6ea0b67b21dc004687')], ['$set' => ['some_property' => 'some_value']]);

Categories