2017-03-26 43 views
1

我遇到了php和MongoDB的問題。這裏是我的文檔:如何計算嵌入的mongodb php?

"_id" : ObjectId("58d7815f387e76880c000000"), 
"receiver" : "Katty", 
"chat" : [ 
       { 
         "sender" : "jhon", 
         "date" : ISODate("2017-03-26T08:53:55Z"), 
         "message" : "Who are you?" 
         "status" : "sent" 
       }, 
       { 
         "sender" : "jhon", 
         "date" : ISODate("2017-03-26T08:53:55Z"), 
         "message" : "What do you want?" 
         "status" : "pending" 
       } 
       { 
         "sender" : "jhon", 
         "date" : ISODate("2017-03-26T08:53:55Z"), 
         "message" : "Hah ?" 
         "status" : "pending" 
       } 
] 

這是我的PHP程序:

<?php 
$conn = new Mongo(); 
$db = $conn->selectDB('basarnas'); 
$query = $db->informasi_bencana; 
$nosql = array("_id"=> new MongoId($id), "chat.status"=>"pending"); 
$result = $query->find($nosql); 
$beritasar = $result->count(); 
$total = $beritasar; 
echo "status pending = ".$total; 
?> 

,其結果是

status pending = 1 

而且我要的結果是

status pending = 2 

如何具有statu時的嵌入式文檔的計數s =「待定」?

+0

因爲您正在提取主文檔(只有一個),而不是子文檔。你的查詢基本上是這樣說的:「獲取所有包含狀態爲」正在等待「的子文檔的文檔 –

+0

是的,我認爲是這樣,我能做些什麼來獲取子文檔? –

+0

如果你需要能夠查詢並在「聊天」中分別搜索文檔,它們應該在自己的集合中,因爲你可以嵌套文檔並不意味着它總是一個好主意。根據我的經驗,嵌套文檔會回來並且更經常地咬你 –

回答

0

您可以展開嵌入的文檔,然後匹配狀態,然後使用groupby統計所有文檔。

db.collection.aggregate([ 

         { "$unwind": "$chat"}, 
         {$match:{"chat.status": "pending"}}, 
         { "$group":{"_id":null, count: {$sum:1}}} 
       ]) 

OR

簡化獲取所有文件和統計數組

db.collection.aggregate([ 

         { "$unwind": "$chat"}, 
         {$match:{"chat.status": "pending"}}, 

       ]) 
0

的長度,你可以試試下面的查詢與最新的PHP驅動程序。您可以$filterchat嵌入式文檔的pending狀態,然後$size

<?php 

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

    $pipeline = 
     [ 
      [ 
      '$match' => 
      [ 
      '_id' => new MongoDB\BSON\ObjectID($id), 
      ], 
      ], 
      [ 
      '$project' => 
      [ 
       'count' => [ 
        '$size' => [ 
        [ 
         '$filter' => [ 
         'input' => '$chat', 
         'as' => 'chatf', 
         'cond' => [ 
          '$eq' => [ 
           '$$chatf.status', 'pending', 
           ] 
          ], 
         ], 
        ], 
       ], 
       ], 
       '_id' => 0 
      ], 
     ], 
    ]; 

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

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

    foreach($cursor as $key => $document) { 
     var_dump($document); 

    } 
?>