如何使用MongoDB PHP库仅返回匹配的数组项

时间:2019-02-13 22:11:20

标签: mongodb php-mongodb

我是MongoDB的新手,目前正在使用Atlas托管的MongoDB。

我的代码使用PHP MongoDB库。

数据库有一个名为“ transactions”的集合,其结构如下:

[  
   {  
      "product":"X",
      "customer":"John",
      "history":[  
         {  
            "payment_date":"2017-07-01",
            "status":"paid"
         },
         {  
            "payment_date":"2017-08-02",
            "status":"paid"
         },
         {  
            "payment_date":"2017-09-03",
            "status":"paid"
         }
      ]
   },
   {  
      "product":"Y",
      "customer":"Mary",
      "history":[  
         {  
            "payment_date":"2017-07-01",
            "status":"paid"
         },
         {  
            "payment_date":"2017-08-02",
            "status":"paid"
         },
         {  
            "payment_date":"2017-09-03",
            "status":"paid"
         }
      ]
   }
]

基于此答案https://stackoverflow.com/a/39549711/1229477,我有以下代码尝试查找付款日期等于2017-08-02的历史记录

$manager = new \MongoDB\Driver\Manager(getenv('MONGODB_DSN'));
$db = new \MongoDB\Database($manager, getenv('MONGODB_DATABASE'));
$cursor = $db->transaction->find(
    ['history.payment_date' => '2017-08-02'],
    ['_id' => 0, 'history' => ['$elemMatch' => ['history.payment_date' => '2017-08-02']]]
);
return $cursor->toArray();

但是它不返回任何项目!

我尝试在MongoShell中运行代码!

我还尝试了一些使用聚合的代码:

$manager = new \MongoDB\Driver\Manager(getenv('MONGODB_DSN'));
$db = new \MongoDB\Database($manager, getenv('MONGODB_DATABASE'));
$cursor = $db->transaction->aggregate(
    [
        [
            '$match' => [
                'history.payment_date' => "2017-08-02"
            ]
        ],
        [
            '$project' => [
                '_id' => 0,
                'history' => 1
            ]
        ]
    ]
);
return $cursor->toArray();

我跟踪了很多链接,但其中任何一个都没有成功! 因此,如果您不给我其他链接,我们将不胜感激,因为我已经访问了数百个!

1 个答案:

答案 0 :(得分:1)

我会尝试一下:

$cursor = $db->transaction->aggregate(
    [
        [
            '$match' => [
                'history.payment_date' => "2017-08-02" // limit returned documents to ones with matches
            ]
        ],
        [
            '$unwind' => "$history" // split each document into multiple documents based on history
        ],
        [
            '$match' => [
                'history.payment_date' => "2017-08-02" // only return documents that match
            ]
        ]
    ]
);