仅根据月份或年份选择文档的查询

问题描述:

是否有查询仅基于MongoDB中的月份或年份选择文档,类似于mysql中以下代码的等效内容;仅根据月份或年份选择文档的查询

$q="SELECT * FROM projects WHERE YEAR(Date) = 2011 AND MONTH(Date) = 5"; 

我在找MongoDB等价物,任何人都可以帮忙吗?

+0

是的,有。问题是什么? – styvane

+0

此代码为mysql。我想要这样的代码MongoDB。 – Serhat

+2

http://docs.mongodb.org/manual/reference/operator/aggregation/year/ – Moritz

使用aggregation framework得到的查询,特别是Date Aggregation Operators$year$month。聚合管道,让你上面的查询应该是这样的:

var pipeline = [ 
    { 
     "$project": { 
      "year": { "$year": "$date" }, 
      "month": { "$month": "$date" }, 
      "other_fields": 1 
     } 
    }, 
    { 
     "$match": { 
      "year": 2011, 
      "month": 5 
     } 
    } 
] 

db.project.aggregate(pipeline); 

等价的PHP查询是:

$m = new MongoClient("localhost"); 
$c = $m->selectDB("examples")->selectCollection("project"); 

$pipeline = array(
    array(
     '$project' => array(
      "year" => array("$year" => '$date'), 
      "month" => array("$month" => '$date'), 
      "other_fields" => 1, 
     ) 
    ),  
    array(
     '$match' => array(
      "year" => 2011, 
      "month" => 5, 
     ), 
    ), 
); 
$results = $c->aggregate($pipeline); 
var_dump($results);