mongodb关于时间date的查询——Querying for a Date Range


来源: http://cookbook.mongodb.org/patterns/date_range/


注意: javascript 中 ,月份是从0开始算起的。 如下面的例子中, start表示 2010-04-01日。

var start = new Date(2010, 3, 1);

Querying for a Date Range (Specific Month or Day)

Credit: Mike Dirolf

Problem

You want to list all of the documents in a collection (in the example we'll use "posts") that were created in a particular month. Each document in the collection has a field representing the date it was created:

{
    "title" : "A blog post",
    "author" : "Mike",
    "content" : "...",
    "created_on" : new Date();
}

We want to perform a query to get all documents whose value for created_on is in the month of April, 2010.

Solution

Use a range query to query for documents whose value for created_on is greater than a Date representing the start of the month, and less than a Date representing the end.

1. Construct Date objects representing the start and end of the month

Our first step is to construct Date instances that we can use to do the range query. In JavaScript:

var start = new Date(2010, 3, 1);
var end = new Date(2010, 4, 1);

Note that in JS the month portion of the Date constructor is 0-indexed, so the start variable above is April 1st and theend variable is May 1st. The logic here is similar in all languages, in Python we'd do:

>>> from datetime import datetime
>>> start = datetime(2010, 4, 1)
>>> end = datetime(2010, 5, 1)
2. Perform a range query

Now that we have our reference dates, we can perform a range query to get the matching documents, note the use of the special $ operators, $gte (greater-than) and $lt (less-than):

db.posts.find({created_on: {$gte: start, $lt: end}});

Again, this translates nicely to other languages - in Python it's:

>>> db.posts.find({"created_on": {"$gte": start, "$lt": end}})
3. Use an index for performance

To make these queries fast we can use an index on the created_on field:

db.posts.ensureIndex({created_on: 1});

We can also use a compound index if we're performing a query on author and a date range, like so:

db.posts.ensureIndex({author: 1, created_on: 1});
db.posts.find({author: "Mike", created_on: {$gt: start, $lt: end}});


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值