mongodb 根据日期返回查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8835757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
return query based on date
提问by coure2011
I have a data like this in mongodb
我在mongodb中有这样的数据
{
"latitude" : "",
"longitude" : "",
"course" : "",
"battery" : "0",
"imei" : "0",
"altitude" : "F:3.82V",
"mcc" : "07",
"mnc" : "007B",
"lac" : "2A83",
"_id" : ObjectId("4f0eb2c406ab6a9d4d000003"),
"createdAt" : ISODate("2012-01-12T20:15:31Z")
}
How do I query db.gpsdatas.find({'createdAt': ??what here??})
, so that it returns the above data result to me from the db?
我如何查询db.gpsdatas.find({'createdAt': ??what here??})
,以便它从数据库返回上述数据结果给我?
回答by mnemosyn
You probably want to make a range query, for example, all items created after a given date:
您可能想要进行范围查询,例如,在给定日期之后创建的所有项目:
db.gpsdatas.find({"createdAt" : { $gte : new ISODate("2012-01-12T20:15:31Z") }});
I'm using $gte
(greater than or equals), because this is often used for date-only queries, where the time component is 00:00:00.
我正在使用$gte
(大于或等于),因为这通常用于仅日期查询,其中时间组件为 00:00:00。
If you really want to find a date that equals another date, the syntax would be
如果你真的想找到一个等于另一个日期的日期,语法是
db.gpsdatas.find({"createdAt" : new ISODate("2012-01-12T20:15:31Z") });
回答by med116
if you want to get items anywhere on that date you need to compare two dates
如果您想在该日期的任何地方获取项目,您需要比较两个日期
You can create two dates off of the first one like this, to get the start of the day, and the end of the day.
您可以像这样从第一个日期创建两个日期,以获得一天的开始和一天的结束。
var startDate = new Date(); // this is the starting date that looks like ISODate("2014-10-03T04:00:00.188Z")
startDate.setSeconds(0);
startDate.setHours(0);
startDate.setMinutes(0);
var dateMidnight = new Date(startDate);
dateMidnight.setHours(23);
dateMidnight.setMinutes(59);
dateMidnight.setSeconds(59);
### MONGO QUERY
var query = {
inserted_at: {
$gt:morning,
$lt:dateScrapedMidnight
}
};
//MORNING: Sun Oct 12 2014 00:00:00 GMT-0400 (EDT)
//MIDNIGHT: Sun Oct 12 2014 23:59:59 GMT-0400 (EDT)
回答by Paul
Just been implementing something similar in Mongo v3.2.3 using Node v0.12.7 and v4.4.4 and used:
刚刚使用 Node v0.12.7 和 v4.4.4 在 Mongo v3.2.3 中实现了类似的东西,并使用了:
{ $gte: new Date(dateVar).toISOString() }
I'm passing in an ISODate (e.g. 2016-04-22T00:00:00Z) and this works for a .find() query with or without the toISOString function. But when using in an .aggregate() $match query it doesn't like the toISOString function!
我正在传递一个 ISODate(例如 2016-04-22T00:00:00Z),这适用于带有或不带有 toISOString 函数的 .find() 查询。但是当在 .aggregate() $match 查询中使用时,它不喜欢 toISOString 函数!
回答by chovy
If you want to get all new things in the past 5 minutes you would have to do some calculations, but its not hard...
如果您想在过去 5 分钟内获得所有新事物,则必须进行一些计算,但这并不难...
First create an index on the property you want to match on (include sort direction -1 for descending and 1 for ascending)
首先在要匹配的属性上创建索引(包括排序方向 -1 表示降序,1 表示升序)
db.things.createIndex({ createdAt: -1 }) // descending order on .createdAt
Then query for documents created in the last 5 minutes (60 seconds * 5 minutes)....because javascript's .getTime()
returns milliseconds you need to mulitply by 1000 before you use it as input to the new Date()
constructor.
然后查询在过去 5 分钟(60 秒 * 5 分钟)内创建的文档。...因为 javascript 的.getTime()
返回毫秒数需要乘以 1000,然后才能将其用作new Date()
构造函数的输入。
db.things.find({
createdAt: {
$gte: new Date(new Date().getTime()-60*5*1000).toISOString()
}
})
.count()
Explanation for new Date(new Date().getTime()-60*5*1000).toISOString()
is as follows:
解释new Date(new Date().getTime()-60*5*1000).toISOString()
如下:
First we calculate "5 minutes ago":
首先我们计算“5 分钟前”:
new Date().getTime()
gives us current time in milliseconds- We want to subtract 5 minutes (in ms) from that:
5*60*1000
-- I just multiply by60
seconds so its easy to change. I can just change5
to120
if I want 2 hours (120 minutes). new Date().getTime()-60*5*1000
gives us1484383878676
(5 minutes ago in ms)
new Date().getTime()
以毫秒为单位给我们当前时间- 我们想从中减去 5 分钟(以毫秒为单位):
5*60*1000
-- 我只是乘以60
秒,所以很容易改变。如果我想要 2 小时(120 分钟),我可以更改5
为120
。 new Date().getTime()-60*5*1000
给我们1484383878676
(5 分钟前以毫秒为单位)
Now we need to feed that into a new Date()
constructor to get the ISO string format required by MongoDB timestamps.
现在我们需要将其输入到new Date()
构造函数中以获取 MongoDB 时间戳所需的 ISO 字符串格式。
{ $gte: new Date(resultFromAbove).toISOString() }
(mongodb .find() query)- Since we can't have variables we do it all in one shot:
new Date(new Date().getTime()-60*5*1000)
- ...then convert to ISO string:
.toISOString()
new Date(new Date().getTime()-60*5*1000).toISOString()
gives us2017-01-14T08:53:17.586Z
{ $gte: new Date(resultFromAbove).toISOString() }
(mongodb .find() 查询)- 因为我们不能有变量,所以我们一次性完成:
new Date(new Date().getTime()-60*5*1000)
- ...然后转换为 ISO 字符串:
.toISOString()
new Date(new Date().getTime()-60*5*1000).toISOString()
给我们2017-01-14T08:53:17.586Z
Of course this is a little easier with variables if you're using the node-mongodb-native driver, but this works in the mongo shell which is what I usually use to check things.
当然,如果您使用的是 node-mongodb-native 驱动程序,这对于变量会更容易一些,但这在 mongo shell 中有效,这是我通常用来检查事物的方法。
回答by Daniel_Madain
You can also try:
你也可以试试:
{
"dateProp": { $gt: new Date('06/15/2016').getTime() }
}
回答by Atul Yadav
If you are using Mongoose,
如果您使用的是猫鼬,
try {
const data = await GPSDatas.aggregate([
{
$match: { createdAt : { $gt: new Date() }
},
{
$sort: { createdAt: 1 }
}
])
console.log(data)
} catch(error) {
console.log(error)
}
回答by Hamit YILDIRIM
Find with a specific date:
查找特定日期:
db.getCollection('CollectionName').find({"DepartureDate" : new ISODate("2019-06-21T00:00:00.000Z")})
Find with greater gte
or little lt
:
查找gte
或多或少lt
:
db.getCollection('CollectionName').find({"DepartureDate" : { $gte : new ISODate("2019-06-11T00:00:00.000Z") }})
Find by range:
按范围查找:
db.getCollection('CollectionName').find({
"DepartureDate": {
$lt: new Date(),
$gte: new Date(new Date().setDate(new Date().getDate()-15))
}
})