2017-02-04 51 views
0

我想在這樣一個數據結構使用PHP蒙戈庫「聚集」:使用「聚合」結合與查詢匹配的所有子文檔的列表?

{ 
    "_id": 100, 
    "name": "Joe", 
    "pets":[ 
     { 
      "name": "Kill me", 
      "animal": "Frog" 
     }, 
     { 
      "name": "Petrov", 
      "animal": "Cat" 
     }, 
     { 
      "name": "Joe", 
      "animal": "Frog" 
     } 
    ] 
}, 
{ 
    "_id": 101, 
    "name": "Jane", 
    "pets":[ 
     { 
      "name": "James", 
      "animal": "Hedgehog" 
     }, 
     { 
      "name": "Franklin", 
      "animal": "Frog" 
     } 
} 

例如,如果我想獲得的所有子文檔,其中的動物是一隻青蛙。請注意,我不希望所有匹配的「超級文檔」(即帶有_id的文檔)。我希望得到一個數組,看起來像這樣:

[ 
     { 
      "name": "Kill me", 
      "animal": "Frog" 
     }, 
     { 
      "name": "Joe", 
      "animal": "Frog" 
     }, 
     { 
      "name": "Franklin", 
      "animal": "Frog" 
     } 
    ] 

我應該使用(在PHP)什麼語法來做到這一點?我知道它與聚合有關,但我找不到與此特定場景匹配的任何內容。

回答

1

您可以使用下面的聚合。 $match來查找數組的值爲Frog$unwindpets數組。 $match其中文件有Frog,最後一步是將group的匹配文件放入數組中。

<?php 

    $mongo = new MongoDB\Driver\Manager("mongodb://localhost:27017"); 

    $pipeline = 
     [ 
      [ 
       '$match' => 
        [ 
         'pets.animal' => 'Frog', 
        ], 
      ], 
      [ 
       '$unwind' =>'$pets', 
      ], 
      [ 
       '$match' => 
        [ 
         'pets.animal' => 'Frog', 
        ], 
      ], 
      [ 
       '$group' => 
        [ 
         '_id' => null, 
         'animals' => ['$push' => '$pets'], 
        ], 
      ], 
     ]; 

    $command = new \MongoDB\Driver\Command([ 
     'aggregate' => 'insert_collection_name', 
     'pipeline' => $pipeline 
    ]); 

    $cursor = $mongo->executeCommand('insert_db_name', $command); 

    foreach($cursor as $key => $document) { 
      //do something 
    } 

?> 
+0

謝謝,這是非常接近我想要的。但是,我如何去匹配多個領域?例如,我想匹配「動物」和「名字?」 (爲了論證,讓我們假設每個人的任意第三個字段不需要匹配)。 – ColonelHedgehog

+0

你需要像這樣的'[pets.animal'=>'青蛙','pets.name'=>'富蘭克林',],'。以下是[比較]的列表(https://docs.mongodb.com/manual/reference/operator/query-comparison/)&[邏輯](https://docs.mongodb.com/manual/reference/operator/query-logical /)運算符,它們可以在'$ match'階段使用。 – Veeram

相關問題