【问题标题】:Query to select documents based only on month or year查询仅基于月份或年份选择文档
【发布时间】:2015-06-23 18:41:15
【问题描述】:
在 MongoDB 中是否存在仅基于月份或年份选择文档的查询,类似于 mysql 中以下代码的等效项;
$q="SELECT * FROM projects WHERE YEAR(Date) = 2011 AND MONTH(Date) = 5";
我正在寻找 MongoDB 等价物,有人可以帮忙吗?
【问题讨论】:
标签:
php
mongodb
mongodb-query
【解决方案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);