How to Return JSON Data from PHP Mongocursor

How to return JSON data from php MongoCursor

You can do this two ways:

echo json_encode(iterator_to_array($customers));

or you can manually scroll through it:

foreach($customers as $k => $row){
echo json_encode($row);
}

Each of MongoDBs objects should have their __toString() methods correctly implemented to bring back the representation of the value.

Decoding JSON using PHP from Mongo

MongoDB does not store the data as JSON.

The document you pasted seems to be copy&paste from the shell. This is not JSON format either.
This format is called Extended JSON - and is how the MongoDB shell represents the data in javascript.
Most examples on the MongoDB website also use this format as it is simple and easy. So rather then have dozens of different output format (for each language driver), the MongoDB official documentations use the shell for demonstrating functionality and output.

The actual underlaying format is called Binary JSON (BSON). You will never see this format and you will never interact with it.

When you interact with MongoDB in PHP all you have to know is that you save a PHP array. The data returned from MongoDB is also a PHP array. The underlaying disk format is not relevant.

You never have to call json_encode() or json_decode().

The $collection->find($query) method returns a object called MongoCursor. You should iterate over this object to get the results, which will be a PHP array.

foreach($collection->find($query) as $result) {
var_dump($result);
}

This code example will var_dump() one result at a time. This result is called a "MongoDB Document" and is similar to "MySQL row". Just like with MySQL, you don't have to know what the underlaying protocol is, or what the underlaying disk format is - that has no affect on you.

I strongly suggest you read the MongoDB PHP Driver tutorial: http://us2.php.net/manual/en/mongo.tutorial.php

This should explain the concept a littlebit better, along with how the driver works :)

Converting MongoCursor to JSON

Assuming you want implicit conversion (like in flavian's answer), the easiest way to join the elements of your list with commas is:

private implicit def buildJsonString(list: List[DBObject]): String =
list.mkString(",")

Which is basically the answer given in Scala: join an iterable of strings

If you want to include the square brackets to properly construct a JSON array you'd just change it to:

list.mkString("[", ",", "]") // punctuation madness

However if you'd actually like to get to Play JsValue elements as you seem to indicate in the original question, then you could do:

list.map { x => Json.parse(x.toString) }

Which should produce a List[JsValue] instead of a String. However, if you're just going to convert it back to a string again when sending a response, then it's an unneeded step.

Retrieving nested element from MongoCursor

You could try

element.expand[String]("i.skuId")

it returns Option[String]

Convert a MongoCursor from -find() to an array

You can use PHP's iterator_to_array function, as suggested in example 1 of the MongoCursor docs:

$jokes = $collection->find();
$jokesArray = iterator_to_array($jokes);

Properly parse a Mongo cursor to PHP

Basically what I did was this.

return json_encode(iterator_to_array($cursor));

But this created the aforementioned object which is not what I needed.

I solved it in this way.

 $i=0;

foreach($cursor as $item){
$return[$i] = array(
'_id'=>$item['_id'],
'nCode'=>$item['nCode'],
'pId'=>$item['pId'],
'nText'=>$item['nText'],
'longText'=>$item['longText'],
'nStatus'=>$item['nStatus'],
'nVType'=>$item['nVType'],
'pushDate'=>$item['pushDate'],
'updateFlag'=>$item['updateFlag'],
'counter' => $i
);
$i++;
}

return json_encode($return);

Getting object instead of results, am I doing something wrong?

the content of your $personnel variable is a MongoCursor object and NOT what you are expecting to be a result array. in order to retrieve values based on your query, you have to iterate each item on that MongoCursor.

e.g.

<?php

$collection = (new MongoDB\Client)->intranet->personnel;
$result = $collection->find();

$personnels = [];

foreach ($result as $personnel) {
// do something to each document
$personnels[] = $personnel;
}

var_dump($personnels);

or you can also use PHP's iterator_to_array function to convert it directly to array.

<?php

$collection = (new MongoDB\Client)->intranet->personnel;
$personnels = iterator_to_array($collection->find());
var_dump($personnels);


Related Topics



Leave a reply



Submit