通过匹配MongoDB中的日期查询嵌入式文档 [英] Querying embedded documents by matching dates in MongoDB

查看:72
本文介绍了通过匹配MongoDB中的日期查询嵌入式文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含电子邮件的数据库,我想使用regex运算符搜索特定日期,并返回该日期发送的所有电子邮件.到目前为止,我已经尝试过了,但是没有返回任何结果.我是regex的新手,不确定我是否正确查询日期.

I have a database containing emails and I want to search for a specific date using the regex operator and return all emails sent on that date. I have tried this so far but it doesn't return anything. I am new to regex and am not sure if I'm querying the date correctly.

db.messages.find({'headers.Date' : $regex : '2001-07-06'}})

下面的示例成功返回了从指定电子邮件地址发送的所有电子邮件.

This example below successfully returned all the emails send from the specified email address.

db.messages.find({'headers.From' : { $regex : 'reservations@merriotts.com' } });

电子邮件包含以下信息:

The emails contain the following information:

headers { content transfer encoding, content type, date, from, message id, mime version, subject, to }

推荐答案

您无需在此处使用正则表达式,类似这样的更简单的方法应该起作用:

You need not make use of regex here, something simpler like this should work:

db.posts.find({"headers.Date": new Date(2001, 06, 06) })

如果您保存在数据库中的日期没有时间(仅是日,月,年),这应该可以工作

This should work if the dates you saved in the DB are without time (just day, month, year)

现在,如果您使用新的Date()保存日期,其中还包括时间部分,那么您需要创建一个日期范围,其中包括该天的所有时刻:

Now if you have dates saved with new Date(), which includes the time components as well, then you need to create a date range which includes all the moments for that day :

db.posts.find( //query for all moments/time of a specific date
  {"headers.Date": {"$gte": new Date(2001, 6, 6), "$lt": new Date(2001, 6, 7)}})

注意-Date的API是Date(YYYY,MM,DD), 从"0"开始计数"month" ,从"0"开始计数从"1"开始.

Note - The API for Date is Date(YYYY,MM,DD) and counting for 'month' starts from '0' and counting for 'date' starts from '1'.

这篇关于通过匹配MongoDB中的日期查询嵌入式文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆