使用php访问mongodb中嵌套对象的对象值

k2fxgqgv  于 2022-11-28  发布在  Go
关注(0)|答案(1)|浏览(167)

尝试获取candidate_id的值并计算一个候选人获得了多少票我如何在php中访问candidate_id并计算它MongoDB结构

{
"_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"
}}}

以int表示的选票显示区域

我试着搜索网络和阅读文档,但没有运气,因为我是MongoDB和PHP的新手
Edit1:共享我的代码以从数据库获取

$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);
vwkv1x7d

vwkv1x7d1#

我假设你已经安装了用于PHP的mongoDb驱动程序,并且能够查询数据库。这是一个先决条件。使用正确的驱动程序和php版本组合,否则它将失败(有时没有错误)
假设基本的已经设置好了,只需将find转换为数组即可:-)这是一种懒惰而快速的方法

$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);

find_array是一个典型的PHP数组,以AND、OR等作为条件

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

祝你好运!

相关问题