2017-06-06 104 views
2

這裏是它沒有嵌入文檔的代碼。Mongodb不用php獲取嵌入文檔

<?php 
    include 'vendor/dbcon.php'; 
     $documentlist = $state -> find(['s_name' => 'West Bengal'], 
      ['projection' => ['_id' => 0, 'places._id' => 1]]); 

    foreach ($documentlist as $doc) { 
    echo $doc["places._id"] . "\n"; 
    } 
?> 

ERROR shows: Notice: Undefined index: places._id in C:\xampp\htdocs\Education\Home.php on line 130

如果代碼是這樣的:

foreach ($documentlist as $doc) { 
     echo $doc["_id"] . "\n"; 
     } 

then ERROR:: Notice: Undefined index: _id in C:\xampp\htdocs\Education\Home.php on line 130

數據庫結構:MongoDB的

db.state.find().pretty() 

{ 
     "_id" : "state1", 
     "s_name" : "West Bengal", 
     "places" : [ 
       { 
         "_id" : "Bardhaman", 
         "pin" : "754216" 
       }, 
       { 
         "_id" : "Jalpaiguri", 
         "pin" : "754217" 
       } 
     ] 
} 

請幫助我,我怎麼能打印所有places._id列表(來自Bardhaman,Jalpaiguri)

+0

您不包括'_id'。看到? '_id'=> 0' –

+0

我的不好。 「地方」當然是一個陣列。您需要在文檔中對其進行迭代。 –

回答

0

投影沒什麼問題,它只是訪問的符號是PHP符號,而不是PHP中的「Dot notation」。當然還有 「地方」 是一個數組,所以你需要遍歷:

$documentlist = $state->find([],[ '_id' => 0, 'places._id' => 1 ]); 

    foreach ($documentlist as $doc) { 
    foreach($doc['places'] as $place) { 
     echo $place['_id'] . "\n"; 
    } 
    } 

產地:

Bardhaman 
Jalpaiguri 
+0

謝謝你的工作 – Nakul23