trying to get the value of candidate_id and count how many votes has been voted for a candidate
how do I access the candidate_id in php and count it
MongoDB Structure
Hello @Firas_Albusaidy and Welcome to the MongoDB community forums!
Could you tell us more about your data?
I was curious to know why ‘Blocks’ was not an array of objects? Also, how many blocks do you think that object would contain? (there’s a 16MB size limitation for MongoDB documents. It’s quite large, but not infinite)
Hi Hubert,
it was an array but I thought I couldn’t access it unless it is an object ,no more blocks will be added
this is just for demonstrating my graduation project
I will update the code of Blocks to be an array on top
I see! Thank you.
If you use an array, you’ll be able to load the array (or the whole document) from MongoDB to PHP and loop over all the PHP objects in the array as usual.
That said, I would encourage you to learn about our MongoDB Aggregation Pipeline that could also be used to to perform computations like the one you seek. When data grows large enough, it’s not always convenient (or possible) to compute values on the client.
It’s a more advanced topic, but we have great tutorials and free courses to learn about this. They will teach you the technical foundations in the relevant order to learn efficiently. I have gone through a similar training and loved it!
the results you’re getting are MongoDB document objects that are based on BSON. BSON is an important concept to learn, especially if your data is strongly typed. However, it looks visually complex when using var_dump() as it encodes a lot of information about data type.
Individual properties can be accessed as follow. I’m assuming that Blocks is an array, as previously discussed.
// find a specific object
$filter = [ '_id'=> new \MongoDB\BSON\ObjectId("637a7e16e490c4baadd9437f") ];
$cursor = $collection->find($filter);
foreach($cursor as $document)
{
// accessing properties of the MongoDB document. first element directly
$candidate_id = $document->Blocks[0]->candidate_id;
// via a lopp
foreach( $document->Blocks as $block ) {
$candidate_id = $block->candidate_id;
}
// convert MongoDB document to PHP Object via JSON conversion
$phpobject = json_decode( json_encode( $document ) );
foreach($phpobject->Blocks as $block)
{
$candidate_id = $block->candidate_id;
}
}
using json_decode( json_encode( $document ) ); you can convert the document to a PHP object via JSON translation, but it’s important to note that some internal typing information will be lost.
The PHP object is easier to look at in a debugger or with var_dump, but as you can see, how to access the properties is similar to how you would do it with the MongoDB document