日期查询适用于_id,但不适用于日期值-MongoDB [英] 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.
我有一个MongoDB集合,它的日期值是"scrape_systemTime"
,我要用scrape_systemTime : new Date()
插入它.
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)}})
应该返回一组看起来像下面的Object的文档,但是什么也不返回. (请查看"scrape_systemTime"
属性,该属性的日期早于一周.)
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"
}, ...]
但是如果我将_id
用于日期条件,即使用一个星期的时间戳创建ObjectId()
并在查询中使用如下:
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')}})
它返回预期的结果.
为什么会这样?第一种查询语法有什么问题吗?
Why is this happening? Is anything wrong there in the first query syntax?
谢谢.
推荐答案
文档中的scrape_systemTime
字段是字符串,而不是Date
,这说明了您的查询无法正常工作的原因.
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()
这篇关于日期查询适用于_id,但不适用于日期值-MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!