Like queries in MongoDb Using PHP - php

I want to use like queries for search in my app using MongoDb With PHP but I did not get the proper result.
Code:
$query = array("first_name" => "/.*a.*/" );
$updateResult = $this->dbCustomer->find($query);

Try this,
$query = array("first_name" => array("$regex" => "/.a./"));
$updateResult = $this->dbCustomer->find($query);
more details, please check this out

I got an answer and I try this and it's work perfect :
$query = array(array("first_name" => new MongoDB\BSON\Regex("$search_text", 'i')))

Related

projection with array in php mongodb

I have a collection with entries like:
"Name":"test",
"Description":"some desc here",
"Teams":[0:"idhash1",1:"idhash2"],
"clientId":"clienthash"
from which I return all items like this:
$filter = array('clientId' => $clientID);
$options = [];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $this->conn->executeQuery('dbname.collectionname', $query);
Now I want to add another filter on team value:
$filter = array('clientId' => $clientID,'Teams'=>'idhash1');
$options = [];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $this->conn->executeQuery('dbname.collectionname', $query);
which obviously doesn't work. How would I get this to work? I am on PHP7.0, MongoDB 4.0 and extension version 1.4.2
This would be helpful
$insert in MongoDB with Php
http://php.net/manual/en/mongocollection.insert.php
What I decided to do was add the teamid's not only in an array but also as separate keys:
"Name":"test",
"Description":"some desc here",
"Teams":[0:"idhash1",1:"idhash2"],
"clientId":"clienthash",
"Team_idhash1":1,
"Team_idhash2":1
Making querying them very easy and it performs a lot better this way filtering on a team.

How to generate a JSON objet in PHP with two arrays inside

I´m trying to create my own leaderboards sytem for my games so I´m working with PHP and requesting info with Ajax into the games, but as I´m not good at all with PHP I´m pretty confused about how to create a JSON object with all the info I need to handle in the javascript part.
What I want to do, in the PHP part is to generate this JSON object:
{players: ["name1", "name2", ..., "name10"], scores:[score1, score2, ..., score10]}
So I can work in javascript with something like
dataReceived.players[0]
I´m storing and getting the data correctly from the database but I´m not being able to generate that JSON object to receive in the Ajax request. Basically, this is my PHP code:
$query = "SELECT * FROM leadersboards ORDER by score ASC LIMIT 10";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$result_length = mysql_num_rows($result);
$arrayScores = array();
$arrayPlayers = array();
for($i = 0; $i < $result_length; $i++){
$row = mysql_fetch_array($result);
array_push($arrayPlayers, $row['player']);
array_push($arrayScores, $row['score']);
}
$answer = json_encode(array('item' => $arrayPlayers, 'item' => $arrayScores), JSON_FORCE_OBJECT);
Sorry if I made something stupid in PHP, as I said, I don´t know PHP at all, just pretty basic stuff.
The problem is:
array('item' => $arrayPlayers, 'item' => $arrayScores)
You are overwriting the item key right after you set it.
I think you want to do something like this
$answer = json_encode(array('players' => $arrayPlayers, 'scores' => $arrayScores)
Ok, so I fixed it this way, I don´t know if is the best option but it works
$myObject = new stdClass();
$myObject = array(
"players" => $arrayPlayers,
"scores" => $arrayScores,
);
echo json_encode($myObject);
Please stop using mysql_* instead use mysqli_* or PDO.
As per your expected out put of arrays inside object use the below code:
$answer = json_encode(array('players', 'scores'));
$answer->players = $arrayPlayers;
$answer->scores= $arrayScores;

Yii2 mongodb query select query

For example, I have this MongoDB:
In yii2, I want to write a query to find an email = 'abc'. I have this code:
$query->select([])->from('Post')->where(['Comments.Email' => 'abc']);
But it does not work; please help me, as I'm beginner in Yii2 and MongoDB.
You can try this
Document::find()->where(["comments"=>["document"=>["email"=>"abc"]]])->all();
$res = $collection->find(["comments.email"=>"abc"]);
$rows = $res->toArray();
From documentation:
https://www.yiiframework.com/extension/yiisoft/yii2-mongodb/doc/api/2.1/yii-mongodb-collection#find()-detail
You can do that but using this query below,
$order = (new Query)->select([])->from('post')->where(['email' => 'abc'])->all();

ZF2 - bind array to single database query parameter

I'm trying to run a simple query against a Zend\Db\Adapter\Adapter instance. Some sample code:
$sql = "DELETE FROM Goals WHERE match_no = ? AND event_id NOT IN (?) ";
$res = $this->adapter->query($sql, array($matchNo, $goalIds));
return $res->getAffectedRows();
This won't work unfortunately, as the array $goalIds isn't quoted as a list for the IN () part of the SQL, but instead is placed in the SQL as 'Array'.
I've searched and search, and also played with the ZF2 ParameterContainer, but can't work out how to quote an array into a single parameter of comma separated values like this.
I'm pretty sure this could work if I used DB Select functionality, but I'd rather just keep to plain old SQL and parameter for these type of quick queries.
Any help much appreciated.
:wq
Assuming you are using MySQl Adapter, You can do things in the Zend way by writing this:-
use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Sql;
use Zend\Debug\Debug;
$config = array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=database;host=localhost;charset=utf8',
'user' => 'root',
'pass' => 'password',
);
$adapter= new Adapter($config);
$sql = new Sql($adapter);
$select = $sql->select();
$select->from('Goals');
$select->where->notin('match_no', array($matchNo, $goalIds));
$select->where->notin('event_id', array($matchNo, $goalIds));
$selectString = $sql->getSqlStringForSqlObject($select);
$results = $adapter->query($selectString, $adapter::QUERY_MODE_EXECUTE);
Debug::dump($results);

mongo count(*) with php but without sending all result array

I am writing my scripts in PHP and I try to convert SQL
SELECT COUNT(*) AS Rank
FROM user
WHERE user.lvl > $user_level
query to Mongo.
I found only one decision:
$nosql = array(
'lvl' => array('$gt' => $user_level)
);
$result = $collection->find($nosql);
$length = count(iterator_to_array($result));
get all objects which satisfy the condition
And count them in PHP
It is possible to get count of needed objects without sending all array?
mongodb can count result like this you didn't need to use count(iterator_to_array($result));
$nosql = array(
'lvl' => array('$gt' => $user_level)
);
$result = $collection->find($nosql);
$length = $result->count();
The new driver does not implement $cursor->count() use $collection->count() instead
$collection->count($filter)

Categories