MongoDB PHP query LIKE

Bismillaahirrohmaanirrohiim…

Berikut ini query mysql untuk like:

select * from namatabel where namakolom LIKE '%katakunci%' order by kolomsort DESC LIMIT 0, 10

Untuk digunakan di mongoDB php, kita gunakan:

<?php
$dbName = 'namadb';
$tableName = 'namacollection';

$kolom = 'kolomygdicari';
$keyword = 'katakunci';
$sortby = 'kolomsort';
$limit = 10;
$skip = 0;

$returns = array();

$manager = new MongoDB\Driver\Manager();


$filter = array($kolom=> new MongoDB\BSON\Regex($keyword, 'i'));
$options = array('limit'=>$limit,'skip'=>$skip,'sort'=>array($sortby=>-1));

$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery($dbName.'.'.$tableName, $query);

$cursor->setTypeMap(['root' => 'array', 'document' => 'array', 'array' => 'array']);
$cursor = $cursor->toArray();

foreach ($cursor as $document) {
    $document['_id'] = (array) $document['_id'];
    $returns[] = $document;
}

echo '<pre>';
print_r($returns);
echo '</pre>';
echo '<hr />';

Untuk lebih memahami tentang mapping query mysql dengan mongoDB bisa cek link berikut ini

https://docs.mongodb.com/manual/reference/sql-comparison/

db.people.find( { user_id: /bc/ } )
atau
db.people.find( { user_id: { $regex: /bc/ } } )
atau start with
db.people.find( { user_id: /^bc/ } )

Demikian terimakasih, semoga bermanfaat.

Baca Juga:   Cara install PHP driver mongoDB secara manual

Bagikan

You May Also Like

About the Author: rasupe

Leave a Reply

Your email address will not be published. Required fields are marked *