How can I make a query on mongodb that says: currentTime <= endDate + 7 days or endDate + 7 days >= currentTime?
If I do something like this endDate: { $lte: (current + 7 days) } (ignore the date calculation) it will grab all records from beginning that the endDate less than 7 days from now.
Basically I want to find records that is not ended yet after 7 days from the end date.
try this "endDate" : { "$lte" : new Date(ISODate().getTime() - 1000 * 3600 * 24 * 7) }
Related
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.
I am using mongoose to query data for my node.js application for a given month where I accept the input for a year and month from the user.
This is what I am doing
var lastDay = 31
if (month == 3 || month == 5 || month == 8 || month == 10) lastDay = 30
else if (month == 1) lastDay = 28
var cookies = await Cookies.find({
docDate: {
"$gte": new Date(parseInt(year), parseInt(month), 1),
"$lte": new Date(parseInt(year), parseInt(month), lastDay)}}).sort("docDate");
When I try to query the db for the month of february, I am getting results only uptil the 26 Feb and the result also includes data from january.
Please help me figure out what I am doing wrong.
I think the issue is with the date that is passed to the query.
new Date(2021,01,01); --> 2021-01-31T16:00:00.000Z
new Date(Date.UTC(2021,01,01)); --> 2021-02-01T00:00:00.000Z
If the date field in the database is in UTC then try using new Date(Date.UTC(year, month, day))
Use moment.js library:
docDate: {
"$gte": moment().startOf('month').toDate(),
"$lte": moment().endOf('month').toDate()
}
moment() is the current time. In order to input specific day, use moment(year + '-' + month, "YYYY-MM") for example.
I'm trying to get the date a record/document was inserted into a MongoDB collection. I'm using the ObjectId.getTimestamp() function to get the timestamp from the date.
The function returns an ISODate object, and going through this question, it looks like ISODate is just a wrapper around the native JavaScript Date. But when I use the getDay() and getMonth() methods on the ISODate object, it returns incorrect results, though hours, minutes and year seems fine.
Usage (Mongo shell) -
> db.user.count()
1
> db.user.findOne()._id.getTimestamp()
ISODate("2018-10-26T12:52:31Z")
> db.user.findOne()._id.getTimestamp().getDay()
5
> db.user.findOne()._id.getTimestamp().getMonth()
9
> db.user.findOne()._id.getTimestamp().getFullYear()
2018
> db.user.findOne()._id.getTimestamp().getHours()
12
> db.user.findOne()._id.getTimestamp().getMinutes()
52
>
According to this -
> db.user.findOne()._id.getTimestamp().getDay()
5
> db.user.findOne()._id.getTimestamp().getMonth()
9
day is 5 and month is 9, but it should be 26 and 10 respectively.
Screenshot -
What am I doing wrong?
Date.getDay() returns day of the week (0-6, being 0 - sunday, 1 - monday, etc...), but Date.getDate() returns day of the month.
db.user.findOne()._id.getTimestamp().getDate()
26
For Date.getMonth(), JavaScript Date return values 0 - 11, being 0 - january, 1 - february, etc.. 9 - october.
db.user.findOne()._id.getTimestamp().getMonth() + 1
10
LINK https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Getter
is there a way to get these information from two dates:
calculate month between dates ( month for me is a complete month)
calculate rest of days between dates
here is my example:
start date:
01/01/2014
end date:
21/02/2014
i need a resualt like this : months:1 days:20
onother example:
start date:
15/01/2014
end date:
10/03/2014
i need a resualt like this : months:1 days:25
Using Java8 Date/Time API you may do it like so,
LocalDate startDate = LocalDate.of(2014, 1, 1);
LocalDate endDate = LocalDate.of(2014, 2, 21);
Period period = startDate.until(endDate);
System.out.println("months: " + period.getMonths() + " days: " + period.getDays());
Data in MongoDB collection has format
{ "_id" : ObjectId("57a1bfc103c8851a98dba3b2"), "createdOn": NumberLong("1470218177561"), "name": "Raja", "description": "Employee Raja" }
Mongo DB Query and Results
> new Date(1470218177561);
ISODate("2016-08-03T09:56:17.561Z")
> new Date(1888888888888);
ISODate("2029-11-09T03:21:28.888Z")
> db.employee.find("{createdOn: { $lt: new Date(NumberLong(1888888888888)) }}");
The last query returns no result without any errors, so I can't determine what is wrong with my query.
Basically, want to find the records for the last 5 days with `$lt operator in Jongo. Tried the next query, but it also not working
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -5);
Date dateBefore = cal.getTime();
collection.find("{createdOn: {$gte : #}}", dateBefore).as(type);
Thanks.
You are comparing
NumberLong("1470218177561") vs new Date(NumberLong(1888888888888))
instead of comparing
NumberLong("1470218177561") vs NumberLong(1888888888888)
In your particular case the query will be
db.employee.find( { createdOn: { $lt: NumberLong(1888888888888) } } );
To find documents that are 5 days old you can look at.
To get current date in milliseconds
> new Date(new Date()).getTime()
1470232681000
To find 5 days old documents use $gt operator on the date that is 5 days before now
> new Date(new Date()).getTime() - 5 * 24 * 60 * 60 * 1000
1469800939000
So the query will be
db.employee.find( { createdOn: { $gt: new Date(new Date()).getTime() - 5 * 24 * 60 * 60 * 1000 } } );
To get the same result with Jongo
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
employees.find("{ createdOn: { $gt: # } }", cal.getTimeInMillis() - 5 * 24 * 60 * 60 * 1000);
The problem with your query for Jongo was the same. You were trying to find by Date type, but date field of documents in your collection is NumberLong, that is millisecond long representation of Date type.
You cannot compare 2 different types with operators like $gt.