2014-04-02 59 views
0

項目我使用這個代碼從我的MongoDB檢索新聞條目:使用PHP,如何檢索匹配創建年份和月份

的foreach(集(「新京報」) - >查找([」創建「=> $時間])爲$新聞)

現在我想找到只與那些新聞文章‘創造’Unix時間戳的具體年份的特定月份相匹配,如2014年4月

任何幫助,將不勝感激。

乾杯。

編輯:謝謝大家的努力,是的,它是unix時間戳。

+0

它是一個UNIX時間戳或BSON日期? – Sammaye

回答

0

你就必須建立自己的查詢:

SELECT * FROM news WHERE created >= $start_date AND created <= $end_date

其中:

假設創建爲UNIX時間戳,否則你應該跳過strtotime功能

// first day of april 2014 
$start_date = strtotime(date('2014-04-01')); 

// last day of april 2014 
$end_date = strtotime(date('2014-04-t')); 
0

你可以使用DateTime::createFromFormat來創建您的時間戳。

$begin = DateTime::createFromFormat('!Y-m', '2014-04'); 
$end = clone $begin; 
$end->modify('next month'); 

echo $begin->format('Y-m-d H:i:s'). PHP_EOL; // 2014-04-01 00:00:00 
echo $end->format('Y-m-d H:i:s');   // 2014-05-01 00:00:00 

並構建更復雜的condition

collection("news") 
    ->find(["created" => array(
     '$gte' => $begin->getTimestamp(), 
     '$lt' => $end->getTimestamp())]); 
+0

謝謝仙人掌。這是有點工作,這意味着find()只拾取$ gte並顯示在特定日期之後創建的項目。 $ lt和/或array()完全被忽略。 正確定義$ begin和$ end。 –

1

你是如何創建Unix時間戳的?它在文檔中如何表示? 您使用MongoDate類型還是使用integer

如果您使用的是MongoDate類型,那麼你需要構建MongoDate對象並用它們爲您$gte$lt條件

$article = array(
    "title"  => "My first article", 
    "content" => "This is good news", 
    "published" => new MongoDate(), 
    "author" => "Random guy on the internet", 
); 

$collection->insert($article); 

$start = new MongoDate(strtotime("yesterday")); 
$end = new MongoDate(strtotime("tomorrow")); 

$cursor = $collection->find(array("ts" => array('$gt' => $start, '$lte' => $end))); 

foreach($cursor as $article) { 
    var_dump($article); 
} 

http://www.php.net/manual/en/class.mongodate.php更多信息