Best way to get documents in specific timeframe MongoDB - mongodb

I am creating a script that would run after every x minutes and needs to gather data from MongoDB by timestamps.
For example, how would I match the documents with aggregation that have a timestamp in the following timeframe:
start_time = current_time - 60 min
end_time = start_time + 30 min
And I would need to get all the documents that stay within that time frame.
The MongoDB objects have ISODate timestamps on them.
Thanks!

You can create date objects in mongo shell like so:
db.getCollection('order').aggregate([
{
$match : {
start_time : {$gte : new Date(ISODate().getTime() - 1000 * 60 * 60)},
end_time : {$lte : new Date(ISODate().getTime() + 1000 * 60 * 30)}
}
}
...
])
You can use this in aggregate but also in normal find queries.
Note I wrote this without testing, so it might have syntax errors..

db.collection.find({"createdAt": { $gt: new Date('2017-04-25')},"updatedAt":{$lt:new Date('2017-06-25')}})
updatedAt and createdAt are the feilds I have taken at the time of designing the schema by timestamp. You could give feilds according to you design.
the find query would be little better than aggregate in this case as no complex functions have to be performed

Related

Mongo DB query - Transform unix date from document in Date Object to compare

I want make a query to return all documents from a collection created in that day.
This is what i done so far:
db.entities.find({"creDate":{"$gte": new Date(Date.now() - (1000 * 60 * 60 * 24))}});
The problem is that the atributte "creDate" format is unix. Example: 1653408094.1847994
So, in the above query i need to convert "creDate" to Date Object.
Thanks!

getting updated records from last 2 hours

I have a large amount of data in my MongoDB and I want to query those records which were updated in the last 2 hours. can someone help
Pretty simple actually. First, add an updatedAt attribute at your collection. But I assume that you already have this.
So, in short:
db.collection.find({ "updatedAt" : { $lt: new Date(Date.now() - 2 * 60 * 60 * 1000) } })
If you did not have an updatedAt attribute, then this one is also possible.
db.collection.find({ $where: function () {
return Date.now() - this._id.getTimestamp() < (2 * 60 * 60 * 1000)
} })
Explanation:
You will find all documents whose updatedAt attribute is less than 7200 seconds.
You will find all documents whose ObjectID is less than 7200 seconds.
Remember that ObjectID's timestamp can be retrieved.

Looking for function similar to "BETWEEN" in MongoDB

I need to get all records from MongoDB collection "employee" where joining_date is between current_date and current_date + 5 days. I couldn't find anything similar to BETWEEN operator in MongoDB documentation. Below query works fine in Google BigQuery. Looking for similar solution in MongoDB.
select * from employee where joining_date BETWEEN current_date() and DATE_ADD(current_date(), interval 5 DAY);
The $gt and $lt Comparison Query Operators can be used to find matches within a range of dates. Here's one approach.
db.employee.find({
"joining_date": {
$gt: new Date(),
$lt: new Date(new Date().setDate(new Date().getDate() + 5))
}
})

Query mongo on timestamp

I want to query Mongo based on timestamp. Follwing is the field in mongo.
"timestamp" : "2016-03-07 11:33:48"
Books is the collection name and below is my query for time period of 1 minute:
db.Books.find({"timestamp":{$gte: ISODate("2016-03-07T11:33:48.000Z"), $lt: ISODate("2016-03-07T11:34:48.000Z")}})
Also is there any alternative like I don't have to give greater and lower limit on timestamp. But query based time interval mentioned. Something like, if present timestamp is TS = "2016-03-07T11:33:48.000Z" then query should be between TS and TS + 1 minute rather than explicitly mentioning timestamp. Something like adding 1 minute to present timestamp
db.Books.find({"timestamp":{$gte: "2016-03-07 11:33:48", $lt: "2016-03-07 11:34:48"}})
ISODate is not required here

get mongodb records created in a specific month

I'm trying to get a specific range of documents, based on when they were created. What I'm trying to do is something like:
/getclaims/2015-01
/getclaims/2015-02
...
that way a user can browse through all records based on the selected month.
In my database I'm not storing a created_at date, but I know mongodb stores this in the objectid.
I found that I can get records like this:
db.claims.find({
$where: function () { return Date.now() - this._id.getTimestamp() < (365 * 24 * 60 * 60 * 1000) }
})
of course that doesn't filter based on a specific month, but only within a certain time limit.
What would be a possible way of limited a query based on a specific month, using the Timestamp from the objectid's?
I'm using mongoose, but it's probably a good idea to start in mongo shell itself.
Based on the function borrowed from the answer to this question - https://stackoverflow.com/a/8753670/131809
function objectIdWithTimestamp(timestamp) {
// Convert date object to hex seconds since Unix epoch
var hexSeconds = Math.floor(timestamp/1000).toString(16);
// Create an ObjectId with that hex timestamp
return ObjectId(hexSeconds + "0000000000000000");
}
Create a start and an end date for the month you're looking for:
var start = objectIdWithTimestamp(new Date(2015, 01, 01));
var end = objectIdWithTimestamp(new Date(2015, 01, 31));
Then, run the query with $gte and $lt:
db.claims.find({_id: {$gte: start, $lt: end}});