Rename mongo database - php

I am doing project using mongodb and php. so here I tried to rename existing database using php. so I did following way to rename database.
first I create new database( user new database name)
read all records from old db and insert to new db
then I drop old db
this is my code.
$conn = new \MongoClient('mongodb://example.com:27017', array("connect" => TRUE));
$exist_dbs = $conn->listDBs();
foreach ($exist_dbs["databases"] as $databse) {
if ($databse['name'] == $new_name) {
$new_name_is_exist = true;
}
}
if (!$new_name_is_exist) {
$db = new \MongoDB($conn, $old_name);
//create new database
$db_new = new \MongoDB($conn, $new_name);
$collections = $db->getCollectionNames();
foreach ($collections as $collection) {
//create collection
$new_collection = new \MongoCollection($db_new, $collection);
$mongo_collection = $db->$collection;
$objects = $mongo_collection->find();
while ($document = $objects->getNext()) {
//add records
$new_collection->insert($document);
}
}
$db->drop();
$msg = 'database renamed';
} else {
$msg = 'given database name already exist';
}
$conn->close();
it works fine. but I would like to know is there any better way to rename mongo database using php?

Copy db (php + mongodb):
<?php
$rename = 'oldname';
$name = 'newname';
$mongo = (new MongoClient());
$db = $mongo->admin;
$response = $db->command(array(
'copydb' => 1,
'fromhost' => 'localhost',
'fromdb' => $rename,
'todb' => $name
));
print_r($response);
Drop db (php + mongodb):
<?php
$name = 'oldname';
$mongo = (new MongoClient());
$db = $mongo->$name;
$response = $db->command(array(
'dropDatabase' => 1
));
print_r($response);

$db=new new Mongo();
Copy old_db to new_db
$responseCopy = $db->admin->command(array(
'copydb' => 1,
'fromhost' => 'localhost',
'fromdb' => 'old_db',
'todb' =>'new_db'
));
Now drop old_db
if($responseCopy['ok']==1){
$responseDrop=$db->old_db->command(array('dropDatabase' => 1));
//OR
$responseDrop =$db->old_db->drop();
}
Show Output
print_r($responseCopy);
print_r($responseDrop);
Output will be something like this
Array ( [ok] => 1 )
Array ( [dropped] => old_db [ok] => 1 )

you can use this
$mongo = new MongoClient('_MONGODB_HOST_URL_');
$query = array("renameCollection" => "Database.OldName", "to" => "Database.NewName", "dropTarget" => "true");
$mongo->admin->command($query);

Related

how multi update data on codeigniter

how to take the auto increment value to post.
here I insert two tables successfully, I create a condition after insertion, then update the data.
I have two tables, the first 'service' table and the second table 'customer_address'
customer_address table, has id_address as autoincrement.
when inserting data into two tables, I want to get the value id_address in the customer_address table. to be updated to the 'service' table.
public function import () {
include APPPATH.
'third_party/PHPExcel/PHPExcel.php';
$excelreader = new PHPExcel_Reader_Excel2007();
$loadexcel = $excelreader-> load('excel/'.$this-> filename.
'.xlsx'); //here I am loading data from an excel file for import
$sheet = $loadexcel->getActiveSheet()->toArray(null, true, true, true);
$data = array();
$numrow = 1;
foreach($sheet as $row) {
$a['acak'] = $this-> M_order-> bikin_kode();
$resi = $a['acak'];
$key1 = $this-> M_order-> db_cek($row['C']);
$origin = $key1['id_origin'];
if ($numrow > 1) {
array_push($data, array(
'tracking_number' => $resi,
'id_cs' => $row['B'],
'id_origin' => $origin,
'id_muat' => $row['D'],
));
$datax = array(
//'id_alamat' => this autoincrement
'id_cs' => $row['AM'],
'nama' => $row['AN'],
);
$this->db-> insert('customer_address', $datax);
// this update data to table service //
//here I am looping, to retrieve the address_id which was just at POST,
$isi = $this->db-> select('id_alamat')-> from('customer_address')->where('id_kota', $kot)->get()-> result();
foreach($sheet as $value) {
$hsl = array(
'id_muat' => $value - > id_alamat,
);
$this->db->update('service', $hsl);
}
}
$numrow++;
}
$this->M_order->insert_multiple($data); //to table service
}
when I updated the 'service' table I updated everything. how to update based on the data input only?
You must send id_alamat from view to your controller and make a unique code not just using autoincrement.
for example:
public function import () {
include APPPATH.
'third_party/PHPExcel/PHPExcel.php';
$excelreader = new PHPExcel_Reader_Excel2007();
$loadexcel = $excelreader-> load('excel/'.$this-> filename.
'.xlsx'); //here I am loading data from an excel file for import
$sheet = $loadexcel->getActiveSheet()->toArray(null, true, true, true);
$data = array();
$numrow = 1;
foreach($sheet as $row) {
$a['acak'] = $this-> M_order-> bikin_kode();
$resi = $a['acak'];
$key1 = $this-> M_order-> db_cek($row['C']);
$origin = $key1['id_origin'];
if ($numrow > 1) {
array_push($data, array(
'tracking_number' => $resi,
'id_cs' => $row['B'],
'id_origin' => $origin,
'id_muat' => $row['D'],
));
$datax = array(
'id_alamat' => $row['id_alamat'],
'id_cs' => $row['AM'],
'nama' => $row['AN'],
);
$this->db-> insert('customer_address', $datax);
// this update data to table service //
//here I am looping, to retrieve the address_id which was just at POST,
$isi = $this->db->select('id_alamat')->from('customer_address')->where('id_kota', $kot)->get()-> result();
//change $sheet to $isi
foreach($isi as $value) {
$hsl = array(
'id_muat' => $value->id_alamat,
);
$this->db->update('service', $hsl);
}
}
$numrow++;
}
$this->M_order->insert_multiple($data); //to table service
}

PHP solr atomic update

I'm new in solr and I've been using this thread to do a atomic update
How do I update a document in Solr PHP?
Basically im doing an mysql query then update a document on solr
Question: How to do an atomic update where a specific field matches a field should be matched inside an if statement like this:
if(solr(username.field) == 'john'))
{
//execute atomic update
}
so far my code is messy like these:
$query = "SELECT * from User";
$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
'path' => SOLR_SERVER_PATH,
);
$result = $mysqli->query($query);
if($result->num_rows > 0)
{
while($row=mysqli_fetch_assoc($result))
{
$querySearch = '+username:*'; //query all user that is on solr
$query = new SolrQuery();
$query->setQuery($querySearch);
$query->setStart(0);
$query->setRows(10000);
$client = new SolrClient($options);
$query_response = $client->query($query);
$query_response->setParseMode(SolrQueryResponse::PARSE_SOLR_DOC);
$response = $query_response->getResponse();
$doc = new SolrInputDocument();
$counter = $response->response->numFound;
for($x = 0; $x < $counter; $x++)
{
$doc = $response->response->docs[$x]->getInputDocument(); //this gets the old value (refer to thread)
$docs = $query_response->getResponse()->response->docs[$x]->username->values; //how I get the value of users
$second_doc = new SolrInputDocument();
if($docs == get_product($row['USERNAME']))
{
$second_doc->addField('points', $row['POINTS']); //this suppose to update my solr document with those username found
}
else
{
$second_doc->addField('points', "0");
}
$second_doc->merge($doc);
$updateResponse = $client->addDocument($second_doc);
$client->commit();
}
}
It should have been
if(!empty($response->response->docs[$x]->username->values[$x]) == get_product($row['USERNAME']))
{
$doc = $response->response->docs[$x]->getInputDocument();
$second_doc->addField('point', $row['POINT']);
}
else
{
//do other update here
}
//$response->response->docs[$x]->username->values[$x] => get the usernames in the document

Not able to update mongo document with following code

Im using following code to update a mongo document. But its not working when I use $inc in order to increment a counter. It works well if no inc is used.
$arrWhere = array('epa_id' => $objData->request->memo->epa_id);
$arrSet = array(
'pa_response'=>$objData,
'response_status'=>'N',
'modified_datetime'=> getServerTimeStamp(),
array('$inc'=>array('revision_id'=>1)),
);
$arrResult = $objPriorAuth->updatePA($arrWhere, $arrSet);
public function updatePA($arrWhere,$arrSet)
{
global $medDB;
$strCollection = EPA_MASTER;
$dbCollection = $medDB->$strCollection;
$arrReturn = array();
//dump($arrSet);
try
{
$dbCollection->update(
$arrWhere,
array('$set' =>$arrSet),
array('multiple' => true)
);
dump($medDB->lastError());
}
catch(MongoCursorException $mce)
{
$arrReturn['error'] = $mce->getMessage();
logError($mce->getMessage(),DB_ERROR_LOG_FILE_PATH);
}
return $arrReturn;
}
It's wrong syntax, you can't use inc inside set. Try out the following code:
Change options:
$arrSet = array(
'pa_response'=>$objData,
'response_status'=>'N',
'modified_datetime'=> getServerTimeStamp()
);
$arrInc = array('$inc'=>array('revision_id'=>1));
Change update query:
array('$set' => $arrSet, '$inc' => $arrInc);

GAE PHP Datastore Query

For a project I am using Google App Engine's Datastore with PHP, which does not have official documentation.
I used the following guide to successfully be able to add new entities to the datastore, but now I am struggling to get queries working so that I can retrieve data and display it on my web page.
https://gae-php-tips.appspot.com/2013/12/23/getting-started-with-the-cloud-datastore-on-php-app-engine/
Here is my current code:
try {
// test the config and connectivity by creating a test entity, building
// a commit request for that entity, and creating/updating it in the datastore
// $req = createRequest();
// $service_dataset->commit($dataset_id, $req, []);
$req = createQuery();
// printQueryResults($req);
}
catch (Google_Exception $ex) {
syslog(LOG_WARNING, 'Commit to Cloud Datastore exception: ' . $ex->getMessage());
echo "There was an issue -- check the logs.";
return;
}
function createQuery()
{
$gql_query = new Google_Service_Datastore_GqlQuery();
$gql_query->setQueryString("SELECT * FROM 'Notes' WHERE name = 'test1'");
$gql_query->setAllowLiteral(true);
$req = new Google_Service_Datastore_RunQueryRequest();
$req->setGqlQuery($gql_query);
return $req;
}
I want to be able to query my datastore and get all the entities that have a matching name.
I tested successfully this following code adapted, i assume that you are using DatastoreService.php from the guide you mentioned. There must be different ways to parse the query result but here is one ;)
config.php : replace with your credentials
<?php
$google_api_config = [
'application-id' => 'xxxxxxxxxxxxxxx',
'service-account-name' => 'xxxxx#developer.gserviceaccount.com',
'private-key' => file_get_contents('xxxxxxx.p12'),
'dataset-id' => 'xxxxxxxxxxxx'
];
your code adapted
require_once 'config.php';
require_once 'DatastoreService.php';
try {
$req = createQuery();
}
catch (Google_Exception $ex) {
syslog(LOG_WARNING, 'Commit to Cloud Datastore exception: ' . $ex->getMessage());
echo "There was an issue -- check the logs.";
return;
}
// from config.php
$options = $google_api_config;
$datastoreService = new DatastoreService($options);
$result = $datastoreService->runQuery($req, $optParams = []);
$results = $result->getBatch()->getEntityResults();
$items = array();
foreach ($results as $item) {
$item = $item->getEntity()->getProperties();
$items[] = $item['name']['stringValue'];
}
echo '<plaintext>' . print_r($items, true);
function createQuery()
{
$gql_query = new Google_Service_Datastore_GqlQuery();
$gql_query->setQueryString($query = "SELECT * FROM Notes WHERE name = 'test1'");
$gql_query->setAllowLiteral(true);
$req = new Google_Service_Datastore_RunQueryRequest();
$req->setGqlQuery($gql_query);
return $req;
}
Include google/cloud-datastore library via composer as below.
$ composer require google/cloud-datastore
and you can use Query mothod as Example below.
<?php
require 'vendor/autoload.php';
use Google\Cloud\Datastore\DatastoreClient;
$datastore = new DatastoreClient([
'projectId' => 'my_project'
]);
$query = $datastore->query();
$query->kind('Notes');
$query->filter('name ', '=', 'test1');
$res = $datastore->runQuery($query);
foreach ($res as $notes) {
echo $notes['name']; // test1
}
Or it can be build using query object
<?php
$query = $datastore->query([
'query' => [
'kind' => [
[
'name' => 'Notes'
]
],
'filter' => [
'propertyFilter' => [
'op' => 'EQUAL',
'property' => [
'name' => 'name'
],
'value' => [
'stringValue' => 'test1'
]
]
]
]
]);

MongoDB -PHP data update

For save data from form to MongoDB database i'm using this code.
if (isset($_POST))
{
$m = new MongoClient();
$db = $m->abst;
$collection = $db->users;
print_r($_POST);
if($collection->find(array('user_id' => $pid)))
{
$collection->update(array('user_id'=>$pid),$_POST);
}
else
{
$document = array_merge(array('user_id'=>$pid),$_POST);
$collection->insert($document);
}
}
How can check user id exist in collection? and if user id exist in collection, data will update. Otherwise new entry saved to collection. where is the mistake?
Try this - maybe it will work for you.
In MongoDB if a record does not exist for given query and if upsert is true then mongodb adds the record as a new record.
$query['user_id'] = $pid;
$object['$set'] = $_POST;
$options = array('w' => true, 'upsert' => true);
$collection->update($query, $object, $options);
try this
if($collection->find(array('user_id' => $pid))->count() == 1)
{
$collection->update(array('user_id'=>$pid),$_POST);
}

Categories