1

I am constructing a database where I might want to query a day of the week. Is it possible to use mongodb to query days in the week in a datetime (or utc timestamp) field?

Something like; get every object that has a datetime that was on a monday.

If it is not possible then the alternative seems to create dummy variables in the collection that show what day of the week it was. Preferably I would like to only query the datetime object for this as this would keep the database smaller.

cantdutchthis
  • 31,949
  • 17
  • 74
  • 114
  • Related to http://stackoverflow.com/questions/8136652/query-mongodb-on-month-day-year-of-a-datetime – david.storch Sep 20 '13 at 14:28
  • 2
    Depending on what you're trying to do, the aggregation framework has a function for it (http://docs.mongodb.org/manual/reference/aggregation/dayOfWeek/#exp._S_dayOfWeek). – WiredPrairie Sep 20 '13 at 14:49

2 Answers2

1

There are three solutions that I can think of:

  1. Your solution: create an extra "day_of_week" field, either an int or string, and then query against this field rather than the datetime field.
  2. Query for everything in your collection, and then filter the results by day of the week on the client side.
  3. Use $where, passing a javascript function which calls date.getDay(). For example, {$where: function () { return this.date.getDay() == 5; }} for getting every date on a Friday.

Solution #2 would call datetime.date.weekday() in pymongo on the client side. The downside of this method is that every document in the collection will end up being sent over the wire, which could add unnecessary network load. It's better than #1, however, in that it's more space efficient and you don't have duplicated information to keep in sync. Solution #3 has neither of these problems, but $where is slow because it requires the server to create a JavaScript execution context and cannot make use of indexes.

david.storch
  • 661
  • 5
  • 7
0

Pymongo can return Mongo BSON timestamp fields as python datetimes: http://api.mongodb.org/python/current/api/bson/timestamp.html

From there you can call datetime.date.weekday() http://docs.python.org/2/library/datetime.html#datetime.date

jtravaglini
  • 1,676
  • 11
  • 19