Yii2 MongoDB delete single row from document - mongodb

I try this two way to delete but unable to do so:--
Try one:-
$query = new Query();
$query->delete()->from('table_name')->where(['disease_id' => 'A0PO919Q-12', 'status' => 1]);
Try Two:-
$collection = Yii::$app->mongodb->getCollection('table_name');
$collection->delete(['disease_id' => 'A0PO919Q-12']);
Can anyone try to delete data from mongo DB in Yii2 Framewrok

I find the solution
$collection = Yii::$app->mongodb->getCollection('table_name');
$collection->remove(['disease_id' => 'A0PO919Q-12']);

Related

Insert query using foreach

I'm trying to generate a statement sheet. For that, I try to insert data into Mysql using foreach. It works great. But I try to escape the insert query if any duplicate row found in database. I do not want to escape the whole process, but it should escape if a duplicate row found and continue with the next insert query.
$gps = $this->Webmastermodel->acquireStatementDetail();
foreach($gps as $statement){
$insertdata = array(
'product_invoice_id' => $statement['InvoiceNo'],
'PUC' => $statement['productPUC'],
'productQTY' => $statement['productQty'],
'product_sub_total' => $statement['productSubTotal'],
'commissionGain_on_SubTotal' => $statement['commisionChargedOnProductSubTotal']
);
$this->db->insert('partner_business', $insertdata);
}
I would use insert_batch if i were you:
$insertdata = array();
foreach($gps as $statement)
{
$insertdata[] = array(
'product_invoice_id' => $statement['InvoiceNo'],
'PUC' => $statement['productPUC'],
'productQTY' => $statement['productQty'],
'product_sub_total' => $statement['productSubTotal'],
'commissionGain_on_SubTotal' => $statement['commisionChargedOnProductSubTotal']
);
}
$this->db->insert_batch('partner_business', $insertdata);
But since your question is about skipping if a row already exits, you can modify your query and use replace instead:
$this->db->replace('partner_business', $insertdata);
Keeping in mind that its all about providing the right primary_key in your $data array, if there is and existing id it will update its data else it will insert a new row.

PHP \MongoDB\Driver\BulkWrite can't delete _id.$oid Object

I have a script removing Mongo records on PHP7 \MongoDB\Driver as this
$db = new \MongoDB\Driver\Manager(".......");
$bulk = new \MongoDB\Driver\BulkWrite;
$bulk->delete(["_id":"5887e6fda69ca3797f74a4fd"], ['limit' => 1]);
$writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $db->executeBulkWrite('theplace.here', $bulk, $writeConcern);
I also tried
...
$bulk->delete(["_id.$oid":"5887e6fda69ca3797f74a4fd"], ['limit' => 1]);
...
This works for any field I send, it does delete... it just doesn't work when I want to remove an _id _id.$oid, like if it was ignoring without throwing errors.
Any help really appreciated.
You should use a MongoDB\BSON\ObjectID when matching an _id with an ObjectId value. As strings and ObjectIds are not directly comparable:
$bulk->delete(
["_id" => new MongoDB\BSON\ObjectID("5887e6fda69ca3797f74a4fd")],
['limit' => 1]
);

Query builder mongodb index datetime

I'm looking to execute custome query with doctrine odm in fulltext search and datetime range
Indexes are already generated on mongodb
Here is my code :
$search = $dm->createQueryBuilder('VideoBundle:Video');
if (isset($_POST['date']))
{
$from = new \DateTime($_POST['date']);
$to = new \DateTime('today');
$search->field('published')->range($from, $to);
}
$search->expr()->operator('$text', array(
'$search' => $_POST['searchvideo'],
));
$search->limit(50);
$query = $search->getQuery();
$search = $query->execute();
Query returned and executed by Doctrine Mongodb in Symfony profiler is :
db.Video.find().limit(50);
Any help?

Mongodb-PHP: What is the query for retriving record of messages with status unread

I am using neatbeans & using mongodb with php for a webapp. I am retriving messages with following command through php.
include_once '../lib/mongodb/MongoDbConnector.php';
$mongoDb = new MongoDbConnector();
$mongoDb = $mongoDb->getConnection();
$mongoDb = $mongoDb->selectCollection("message");
$countM = $mongoDb->find(array('client_id' => new MongoId($valueU['_id'])), array('status' => 'unread'));
$unreadM = $countM->count();
The query doesnot work. showing me the data & count of messages who have client_id in it.
What to do???
The query is not well formated, it should be like this:
$countM = $mongoDb->find(array('client_id' => new MongoId($valueU['_id']), 'status' => 'unread'));
Also check if $valueU['_id'] is a string or a mongoID object.

How to get affected number of rows using mongodb ,php driver

I have two problem : How can I get affected rows by php mongodb driver ,and how about the last insert id ? thanks .
You can get number of results right from the cursor using count function:
$collection->find()->count();
You can even get number of all records in collection using:
$collection->count();
Using insert method, _id is added to input array automatically.
$a = array('x' => 1);
$collection->insert($a,array('safe'=>true));
var_dump($a);
array(2) {
["x"]=>
int(1)
["_id"]=>
object(MongoId)#4 (0) {
}
}
I don't believe that there is any type of affected_rows() method at your disposal with mongodb. As for the last insert _id You can generate them in your application code and include them in your insert, so there's really no need for any mysql like insert_id() method.
$id = new MongoId();
$collection->insert(array('
'_id' => $id,
'username' => 'username',
'email' => 'johndoe#gmail.com'
'));
Now you can use the object stored in $id however you wish.
Maybe MongoDB::lastError is what you are looking for:
(http://php.net/manual/en/mongodb.lasterror.php)
It calls the getLastError command:
(http://www.mongodb.org/display/DOCS/getLastError+Command)
which returns, among other things:
n - if an update was done, this is the number of documents updated.
For number of affected rows:
$status = $collection->update( $criteria, array( '$set' => $data ) );
$status['n']; // 'n' is the number of affected rows
If you have the output of your action, you can call relative function:
// $m hold mongo library object
$output = $m->myCollection->updateOne([
'_id' => myMongoCreateID('56ce2e90c9c037dba19c3ce1')], [
'$set' => ['column' => 'value']
]);
// get number of modified records
$count = $output->getModifiedCount();
$output is of of type MongoDB\UpdateResult. Relatively check following files to figure out the best function to find inserted, deleted, matched or whatever result you need:
https://github.com/mongodb/mongo-php-library/blob/master/src/InsertManyResult.php
https://github.com/mongodb/mongo-php-library/blob/master/src/DeleteResult.php
https://github.com/mongodb/mongo-php-library/blob/master/src/InsertOneResult.php
https://github.com/mongodb/mongo-php-library/blob/master/src/UpdateResult.php