在MongoDB中是否存在仅基于月份或年份选择文档的查询,类似于mysql中以下代码的等效文档;
$q="SELECT * FROM projects WHERE YEAR(Date) = 2011 AND MONTH(Date) = 5";
我正在寻找MongoDB的等价物,有人可以帮忙吗?
答案 0 :(得分:1)
使用 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);