Querying embedded documents by matching dates in MongoDB

拜拜、爱过 提交于 2019-12-06 12:25:52

问题


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 }

回答1:


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)

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)}})

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



来源:https://stackoverflow.com/questions/27412761/querying-embedded-documents-by-matching-dates-in-mongodb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!