简体   繁体   English

查询以仅基于月份或年份选择文档

[英]Query to select documents based only on month or year

Is there a query to select documents based only on month or year in MongoDB, something like the equivalent for the following code in mysql; 是否有查询来选择仅基于MongoDB中的月份或年份的文档,类似于mysql中以下代码的等效内容;

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

I am looking for the MongoDB equivalent, can anyone help? 我正在寻找等效的MongoDB,有人可以帮忙吗?

Use the aggregation framework to get the query, in particular the Date Aggregation Operators $year and $month . 使用聚合框架来获取查询,尤其是日期聚合运算符 $year$month The aggregation pipeline that gives you the above query would look like this: 为您提供上述查询的聚合管道如下所示:

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

db.project.aggregate(pipeline);

The equivalent PHP query would be: 等效的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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM