0

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!

1 Answer 1

2

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")}})
Sign up to request clarification or add additional context in comments.

3 Comments

nice one that works brilliant an was exactly what i was searching for ! ! ! thanks a lot
@johnSmith Note that though the above code works fine, it's far from being harmless. Because it's using a $project first, it doesn't filter any document from your collection, though you really want to match a single day. Second, the $match can not use dtCreated index if it exists, because it doesn't using data straight from the collection. There is nothing wrong with your approach ($gt & $lt query). If you insist, you can add an extra field for equality whose value is the day of year
I realized that. Unfortunately the date operators aren't available outside the aggregation framework

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.