sohel khalifa
sohel khalifa

Reputation: 5588

Date query works with _id but not with Date value - MongoDB

So, I have been trying this since hours but didn't get any results.

I have a MongoDB collection which has a date value "scrape_systemTime", I am inserting it with scrape_systemTime : new Date().

I am trying to get results that are one week older by using:

db.scrape.find({scrape_systemTime: { $lt: new Date( Date.now() - 86400000*7)}})

Which should return a set of documents that looks like an Object below, but it returns nothing. (Look at the "scrape_systemTime" attribute, which has a week older date.)

[{
        "newspaperID" : "6",
        "scrape_systemTime" : "Fri Oct 25 2013 13:14:10 GMT+0000 (UTC)",
        "_id" : ObjectId("526a6ea1985ba76408000010"),
        "languageID" : "1",
        "scrape_tabs_title" : "India",
        "scrape_tabs_href" : "http://www.indianexpress.com/supplement/India/798/",
        "scrape_thumb" : "images/default/noimage.jpg",
        "scrape_href" : "http://www.indianexpress.com/news/political-parties-woo-chhattisgarh-youth-on-facebook-whatsapp/1187180/",
        "scrape_title" : "Political parties woo Chhattisgarh youth on Facebook, WhatsApp",
        "scrape_largeimage" : "http://static.indianexpress.com/m-images/Fri Oct 25 2013, 17:57 hrs/M_Id_433064_facebook.jpg",
        "scrape_detail_article_text" : "",
        "scrape_newstime" : "PTI : Raipur, Fri Oct 25 2013, 18:11 hrs",
        "scrape_status" : "Pending",
        "viewCount" : 0,
        "error_log" : "OK",
        "ip" : "192.168.0.101"
}, ...]

But if I use the _id for date condition, i.e. create ObjectId() with one week old timestamp and use in query as below:

db.scrape.find({_id: { $lt: ObjectId( Math.floor( new Date( Date.now() - 86400000*7 ) / 1000 ).toString(16) + '0000000000000000')}})

It return expected results.

Why is this happening? Is anything wrong there in the first query syntax?

Image here

Thanks.

Upvotes: 1

Views: 150

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312149

The scrape_systemTime field in your document is a string, not a Date which explains why your query isn't working.

So it must be that you're not inserting your docs as you think you are, as you'd get strings like this if you inserted that field as:

scrape_systemTime: Date()

Upvotes: 3

Related Questions