Find objects between two dates MongoDB Find objects between two dates MongoDB mongodb mongodb

Find objects between two dates MongoDB


Querying for a Date Range (Specific Month or Day) in the MongoDB Cookbook has a very good explanation on the matter, but below is something I tried out myself and it seems to work.

items.save({    name: "example",    created_at: ISODate("2010-04-30T00:00:00.000Z")})items.find({    created_at: {        $gte: ISODate("2010-04-29T00:00:00.000Z"),        $lt: ISODate("2010-05-01T00:00:00.000Z")    }})=> { "_id" : ObjectId("4c0791e2b9ec877893f3363b"), "name" : "example", "created_at" : "Sun May 30 2010 00:00:00 GMT+0300 (EEST)" }

Based on my experiments you will need to serialize your dates into a format that MongoDB supports, because the following gave undesired search results.

items.save({    name: "example",    created_at: "Sun May 30 18.49:00 +0000 2010"})items.find({    created_at: {        $gte:"Mon May 30 18:47:00 +0000 2015",        $lt: "Sun May 30 20:40:36 +0000 2010"    }})=> { "_id" : ObjectId("4c079123b9ec877893f33638"), "name" : "example", "created_at" : "Sun May 30 18.49:00 +0000 2010" }

In the second example no results were expected, but there was still one gotten. This is because a basic string comparison is done.


To clarify. What is important to know is that:

  • Yes, you have to pass a Javascript Date object.
  • Yes, it has to be ISODate friendly
  • Yes, from my experience getting this to work, you need to manipulate the date to ISO
  • Yes, working with dates is generally always a tedious process, and mongo is no exception

Here is a working snippet of code, where we do a little bit of date manipulation to ensure Mongo (here i am using mongoose module and want results for rows whose date attribute is less than (before) the date given as myDate param) can handle it correctly:

var inputDate = new Date(myDate.toISOString());MyModel.find({    'date': { $lte: inputDate }})


Python and pymongo

Finding objects between two dates in Python with pymongo in collection posts (based on the tutorial):

from_date = datetime.datetime(2010, 12, 31, 12, 30, 30, 125000)to_date = datetime.datetime(2011, 12, 31, 12, 30, 30, 125000)for post in posts.find({"date": {"$gte": from_date, "$lt": to_date}}):    print(post)

Where {"$gte": from_date, "$lt": to_date} specifies the range in terms of datetime.datetime types.