2016-03-01 60 views
1

如何在使用PHP的查詢生成器中執行MongoDB連接等效項。 有沒有辦法連接集合。 我認爲如果我們把集合col1中的「_id」的值賦給集合col2中的另一個「model_id」。如何使用PHP在查詢生成器中加入MongoDB集合

「col1集合是正常文檔,col2集合是嵌入文檔」。

實例集合: -

COL1:

{ 
    "_id" : 1, 
    "model_status" : "A", 
} 

COL2:

{ 
    "_id" : 1, 
    "infodetails" : [ 
     { 
      "info_name" : "test", 
     } 
    ],  
    "test_model" : [ 
     { 
      "model_id" : "2", 
      "model_name" : "B", 
     }, 
     { 
      "model_id" : "3", 
      "model_name" : "C", 
     }, 
     { 
      "model_id" : "1", 
      "model_name" : "A", 
     } 
    ] 
} 
+0

任何人都知道上述查詢的解決方案。 – Suresh

回答

1

解決我上面的查詢,這將完美的作品。

====== 
Query:- 
====== 
require_once(MONGODBPATH); 
$mdb = mongoConnection::getMongoConnection(); 
$col2 = $mdb->selectDB("DB")->selectCollection("col2"); 
$ops = array(
      array(
       '$project' => array(
           "_id" => 1, 
           "test_model" => 1, 
          ) 
      ), 
      array('$unwind' => '$test_model'), 
      array(
       '$lookup' => array(
           'from'=>'col1', 
           'localField'=> "test_model.model_id", 
           'foreignField' => "_id", 
           'as'=> "result_foreignField" 
          ) 
      ), 
     ); 
$results = $col2->aggregate($ops); 

========= 
Output:- 
========= 
Array 
(
    [waitedMS] => 0 
    [result] => Array 
     (
      [0] => Array 
       (
        [_id] => 1 
        [test_model] => Array 
         (
          [model_id] => 1 
          [model_name] => A 
         ) 

        [result_foreignField] => Array 
         (
          [0] => Array 
           (
            [_id] => 1 
            [model_status] => A 
           ) 

         ) 

       ) 
     ) 

    [ok] => 1 
)