mongodb关于时间date的查询——Querying for a Date Range
来源:互联网 发布:软件无线电技术应用 编辑:程序博客网 时间:2024/06/05 18:37
来源: 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)
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}});
- mongodb关于时间date的查询——Querying for a Date Range
- 关于时间 date的比较
- Date的用法 关于时间格式
- 关于时间格式转date的问题
- 关于获得时间的Date用法
- jQuery Date Range Picker时间插件API
- php查询oracle date时间
- mongodb 时间类型 date 时间戳等
- date 时间的比较
- Date的时间加减
- JAVA基础—关于Date
- #371 – 指定日历控件显示的日期时间(Specifying a Default Date for a Calendar Control to Display)
- Mongodb 设置过期时间Expire Date
- linux下的时间和日期命令——date
- Date的工具方法——最大最小时间
- 关于java的Date
- 关于JAVA的Date
- 关于date的应用
- 微诺“新婚”一年:相濡以沫 前路未知
- Linux网络驱动程序编写
- GDB资源
- linux内核学习中--"list.h" del move splice 函数理解
- Magento首页添加幻灯片教程
- mongodb关于时间date的查询——Querying for a Date Range
- ESFramework 开发手册(10) -- 安全机制
- Magento任意页面添加Contact Us表单
- C++ 回忆录1
- English - 常用口语
- log4cpp在项目中的封装使用(VC项目)
- getopt 分析命令行参数
- #TC Disrupt NY 2012#SpokenLayer:阅读障碍者的福音
- 分布式数据库的并发控制方法