I have a data like this in 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?
Just been implementing something similar in Mongo v3.2.3 using Node v0.12.7 and v4.4.4 and used:
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!
You can also try:
You probably want to make a range query, for example, all items created after a given date:
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.If you really want to find a date that equals another date, the syntax would be
If you are using Mongoose,
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.
If you want to get all new things in the past 5 minutes you would have to do some calculations, but its not hard...
First create an index on the property you want to match on (include sort direction -1 for descending and 1 for ascending)
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 thenew Date()
constructor.Explanation for
new Date(new Date().getTime()-60*5*1000).toISOString()
is as follows:First we calculate "5 minutes ago":
new Date().getTime()
gives us current time in milliseconds5*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)Now we need to feed that into a
new Date()
constructor to get the ISO string format required by MongoDB timestamps.{ $gte: new Date(resultFromAbove).toISOString() }
(mongodb .find() query)new Date(new Date().getTime()-60*5*1000)
.toISOString()
new Date(new Date().getTime()-60*5*1000).toISOString()
gives us2017-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.