Querying embedded documents by matching dates in M

2020-07-29 03:12发布

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条回答
家丑人穷心不美
2楼-- · 2020-07-29 03:42

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'.

查看更多
登录 后发表回答