john Smith
john Smith

Reputation: 17906

MongoDb Date query without using range?

if i want to find a document created on a specific Day, until now i used a range from the first minute of the day, to the last minute of the day in seconds , sth like :

query":{"dtCreated":{"$gte":{"sec":1381356782,"usec":0},"$lt":{"sec":1389356782,"usec":0}}}

is is possible to to somehow find all documents where only the Day, Month and year equals "dtCreated" ?

in pseudocode like :

query:{"dtCreated":ISODate("2014-01-23")} <- i know that may not be a valid iso date 

but what i want is to find all documents for one day without using lt and gt ?

Sry for bad english and for any hints thanks in advance!

Upvotes: 0

Views: 1804

Answers (1)

Mzzl
Mzzl

Reputation: 4126

You can do it with the aggregation framework using the date aggregation operators. Assuming dtCreated is an ISODate field, you could try something like this:

query = [
    {
        '$project': {
            'year': {'$year':'$dtCreated'}, 
            'month': {'$month':'$dtCreated'}, 
            'day':{'$dayOfMonth':'$dtCreated'}
        }
    }, 
    {
        '$match' : {'year':'2014', 'month':'1', day:'1'}
    }
]

db.mycollection.aggregate(query)

Edit: as orid rightly remarks, though this is an answer to your question (query for date without using date range), it's not a good way to solve your problem. I would probably do it this way: a range greater than or equal to today, but less than tomorrow

db.foo.find({'dtCreated':{'$gte':ISODate("2014-01-23"), '$lt':ISODate("2014-01-24")}})

Upvotes: 2

Related Questions