phparraysmongodbmongodb-queryphp-mongodb

Accessing object value from nested objects in mongodb with php


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

{
"_id":
{
"$oid":"637a7e16e490c4baadd9437f"
},
"civilid":"12769219",
"Blocks":
{
"BaseBlock":
{
"nonce":{"$numberInt":"0"},
"index":{"$numberInt":"0"},
"timestamp":"11-20-2022 22:39:30.082200",
"candidate_id":"0","previousHash":"0",
"hash":"d19f8d1d4bba2c22a82c1f3691f364fac86e992075bbd6a6ad239188d7a242e7"
},
"FirstBlock":
{
"nonce":{"$numberInt":"107675"},
"index":{"$numberInt":"1"},
"timestamp":"11-20-2022 22:39:30.082300",
"candidate_id":"103",
"previousHash":"d19f8d1d4bba2c22a82c1f3691f364fac86e992075bbd6a6ad239188d7a242e7",
"hash":"0000ac30bf8b97a9525d64a10a990ccf2b1fe4ee0c7c91fe665e572f0a39e11f"},
"SeconedBlock":
{
"nonce":{"$numberInt":"124478"},
"index":{"$numberInt":"2"},
"timestamp":"11-20-2022 22:39:30.082300",
"candidate_id":"103",
"previousHash":"0000ac30bf8b97a9525d64a10a990ccf2b1fe4ee0c7c91fe665e572f0a39e11f",
"hash":"0000a709f4faf36466cbd37ec34e09b64db309e306d238b586d4a6ae669f28da"
}}}

the display area in votes in int

I tried searching the web and reading the documents with no luck as I am new in MongoDB and PHP

Edit1:shared my code to get from db

$con = new MongoDB\Client('mongodb+srv://<username>:<password>@<cluster>.ivtq9gb.mongodb.net/?retryWrites=true&w=majority');
$db = $con->VoterDatabase;
$collection3 = $db->Votes;
$cursor3 = $collection3->find(["Blocks"=>"FirstBlock"]);
$result = $cursor3->toArray();
foreach ($result as $row) 
{
$block[] = $row["candidate_id"];
}
var_dump($cursor3);

Solution

  • I assume you have the mongoDb drivers for PHP installed and are able to query the database. That's a prerequisite. Use the right driver and php version combination else it will fail (without errors sometimes)

    Assuming the basic is set up, just convert the find to an array :-) That's the lazy and quick way to do it

    $client = new MongoDB\Client($mongoUrl, [], $mongoOptions);
    $db = $client->$mongoDb;
    $coll = $db->$Ucollection;
    $allUsersArray = $coll->find($find_array)->toArray();
    $allUsersArrayFlat = json_decode(json_encode($allUsersArray), true);
    

    The $find_array is a classic PHP array with AND, OR, etc. as criteria

    $find_array = array(  '$and' => array( array('userName'=> $_POST['userName']), ));
    

    Good luck!