projection with array in php mongodb - php

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.

Related

Fetch more than 100 records on MongoDB with PHP

I'm using the new MongoDB PHP driver. I've been searching how I can get more than 100 records from a query.
I'm using executeCommand to pass the query. I think that in the old driver, the cursor object had a getNext method to get other pages, but It does not have anymore. How can I get the other "pages" from my query?
Simply use MongoDB\Driver\Query and MongoDB\Driver\Manager::executeQuery methods.
Here's a short sample for demonstration:
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$query = new MongoDB\Driver\Query([], []);
$cursor = $manager->executeQuery('DB.Collection', $query);
$array = $cursor->toArray();
Note that resulting $array contains documents (records) as instances of stdClass Object.
I tried this solution and it returns all the documents in collection.
<?php
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$command = new MongoDB\Driver\Command(array('find' => "testColl"));
$cursor = $manager->executeCommand('testDb', $command);
print_r($cursor->toArray());
?>

how to retrive more than 1000 rows in azure tables php

I am trying to get more than 1000 rows from azure in php.
First of all i am not able to use filter class. which namespace need to be added to use filter class
after that while loop is gng in infinite loop
any help
$tableRestProxy = ServicesBuilder::getInstance()->createTableService($this->connectionString);
$filter = "( PartitionKey eq '$id' )";
$options = new QueryEntitiesOptions();
$options->setFilter(Filter::applyQueryString($filter));
$result = $tableRestProxy->queryEntities('test', $options);
$entities = $result->getEntities();
$nextPartitionKey = $result->getNextPartitionKey();
$nextRowKey = $result->getNextRowKey();
while (!is_null($nextRowKey) && !is_null($nextPartitionKey) ) {
$options = new QueryEntitiesOptions();
$options->setNextPartitionKey($nextPartitionKey);
$options->setNextRowKey($nextRowKey);
$options->setFilter(Filter::applyQueryString($filter));
$result2 = $tableRestProxy->queryEntities("test", $options);
$newentities = $result2->getEntities();
$entities=array_merge($newentities, $entities);
}
link m using is
PHP - Azure Table Storage in with more than 1000 entities
You can leverage setTop() function of MicrosoftAzure\Storage\Table\Models\QueryEntitiesOptions class to select the top X (number) entities of the table.
And according the description at https://github.com/Azure/azure-storage-php/blob/master/src/Table/Models/QueryEntitiesOptions.php#L148, we can find that the filter classes have moved into the namespace MicrosoftAzure\Storage\Table\Models\Filters
If you want to use the filter classes in the new Azure Storage SDK for PHP, you can try to include the package as:
use MicrosoftAzure\Storage\Table\Models\Filters\QueryStringFilter;
Please consider the following code snippet:
use MicrosoftAzure\Storage\Table\Models\QueryEntitiesOptions;
use MicrosoftAzure\Storage\Table\Models\Filters\QueryStringFilter;
$options = new QueryEntitiesOptions();
$filter = new QueryStringFilter("(RowKey eq '".$id."')");
$options->setFilter($filter);
$options->setTop(1000);

PHP Query in MongoDB doesn't work

I have been trying to fix this problem since days and I can't really solve it.
I'm trying to use mongo DB for my first time and here's my problem:
$id = utf8_encode($_POST['mongo']);
$query=array("id" => $id);
$conn = new Mongo("mongodb://localhost:27017");
$database = $conn->test;
$collection = $database->pages;
$doc = $collection->findOne($query);
The $id variable is set to 2, but findOne doesn't return anything.
If I try for example to change the id value in array with 2 [$query=array("id" => 2);] the DB returns the document that I need.
It's a mystery ahah.
Can anyone see an error?
Thanks
L
After connect you should be select your document
$id = utf8_encode($_POST['mongo']);
$query=array("id" => $id);
$m = new MongoClient('mongodb://localhost:27017');
$db = $m->selectDB('yourdocumentname');
$collection = new MongoCollection($db, 'yourcollectionname');
$doc = $collection->findOne($query);
var_dump($doc);

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;

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