仅根据月份或年份查询 select 个文档
Query to select documents based only on month or year
在 MongoDB 中是否仅基于月份或年份对 select 文档进行查询,类似于 mysql 中的以下代码;
$q="SELECT * FROM projects WHERE YEAR(Date) = 2011 AND MONTH(Date) = 5";
我正在寻找 MongoDB 的等效项,有人可以帮忙吗?
使用aggregation framework to get the query, in particular the Date Aggregation Operators $year
and $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);
在 MongoDB 中是否仅基于月份或年份对 select 文档进行查询,类似于 mysql 中的以下代码;
$q="SELECT * FROM projects WHERE YEAR(Date) = 2011 AND MONTH(Date) = 5";
我正在寻找 MongoDB 的等效项,有人可以帮忙吗?
使用aggregation framework to get the query, in particular the Date Aggregation Operators $year
and $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);