Is there any query to find data between given dates? - node.js

I am sending the startDate and endDate in the URL and hits the query to find the data between startDate and endDate
var startDate = res.req.query.startDate ? moment(res.req.query.startDate, 'YYYY-MM-DD').valueOf() : null
var endDate = res.req.query.endDate ? moment(res.req.query.endDate, 'YYYY-MM-DD').valueOf() : null
if (startDate && endDate) {
query.dispatchDate = { $gte:startDate , $lte: endDate }
}

You did not clearly asked your question but i am suggestion you a solution what i understand.
In order to find data between 2 dates first you must add a field in db to track when the record is entered let suppose you have a collection named items and field to track when data is enter is created_date then you can find data between 2 dates like
items.find({
created_at: {
$gte: ISODate("2019-01-21T00:00:00.000Z"),
$lt: ISODate("2019-01-28T00:00:00.000Z")
}
})
for more details shHow to find objects between 2 dates in mongodb

Related

ExpressJS: Mongoose query on ISO DATE based on todays date yyyy-mm-dd

I have date something like this
"createdAt": "ISODate('2021-07-07T06:41:46.000Z')"
I have written below mongoose query to fetch records for today. But below query fetched empty.
let meeting = await Meeting.find({
createdAt : {$lt: new Date().toISOString(),$gte: new Date().toISOString()}
});
I have tried below one more way with static date, it worked. I want to fetch data on dynamic todays date.
let meeting = await Meeting.find({
createdAt : {
'$eq': new Date('2021-07-07T06:41:46.000Z')
}
});
Can someone help me on this
I'm assuming the type of "createdAt" field is Date in Mongoose schema (you should convert to Date if it wasn't the case).
Logic
When you want to filter documents on a specific day, you can use the condition:
0:00 the day <= createdAt < 0:00 the following day
For example, to filter meetings on 07/07/2021, the condition will be:
0:00 07/07/2021 <= createdAt < 0:00 08/07/2021
Coding
With that logic in mind, the code is pretty straightforward:
let today = new Date();
today.setHours(0,0,0,0); // set to 0:00
let tomorrow = new Date(today)
tomorrow.setDate(tomorrow.getDate() + 1)
let meeting = await Meeting.find({
createdAt : {$gte: today, $lt: tomorrow}
});
When working with date/time values then I recommend the moment.js library. Could be this one:
let meeting = await Meeting.find({
createdAt : {
$gte: moment().startOf('day').toDate(),
$lte: moment().endOf('day').toDate()
}
});

How to get date difference in mongoDB ? Date should be come in difference of days?

I wants to filter the collection on the basis of subtract expiry date object with current date and which is less than equal to 10 days.
I am using below code but I am getting date difference in millisecond. I want in exact day difference.
db.metaobject.aggregate(
{ $unwind :'$certifications.expiry_date'},
{$project:{
_id:1,name:1,date-Difference: { $divide:[ {$subtract: [ "$certifications.expiry_date",new Date ]},86400000] }
}
},
{$match:{
dateDifference:{$lte:10}
}
}
)
If its to be used in node, you dont need to compute the difference :
Compute directly the date + 10 in node js then just to the $lte :
var date = new Date();
var date10 = new Date(date.getTime());
date10.setDate(date10.getDate() + 10);
db.metaobject.aggregate(
{ $unwind :'$certifications.expiry_date'},
{$match:{
dateDifference:{$lte: new Date(date10).toJSON()}
}
}
)

How to query the data with selected date range in CloudBoost

I want to fetch the records from the CloudTable with particular date range say from : startDate to endDate
We can query all columns including DateTime type in a CloudTable. There are several condition you can add to your query like lessThan, greaterThan etc.
In this case, you can use the following query -
var query = new CB.CloudQuery("TableName");
query.lessThan('dateColumns',"15-12-2016");
query.greaterThan('dateColumns',"15-06-2017");
query.find({
success: function(list) {
//list is an array of CloudObjects
},
error: function(error) {
}
});
Hope it helps.Happy Coding :)

Mongoose date comparison

My application will allow user to create coupons.
Coupon will be valid in datefrom and dateto period.
The thing is that every coupon should be valid for selected days, not hours.
For example since Monday(2016-06-12) to Tuesday(2016-06-13), so two days.
How should I store dates on server side and then compare it using $gte clause in Mongoose?
Thank you :-)
{ "_id" : 1, "couponStartDate" : ISODate("2016-06-26T18:57:30.012Z") }
{ "_id" : 2, "couponStartDate" : ISODate("2016-06-26T18:57:35.012Z") }
var startDate = new Date(); // I am assuming this is gonna be provided
var validDate = startDate;
var parametricDayCount = 2;
validDate.setDate(validDate.getDate()+parametricDayCount);
CouponModel.find({couponStartDate: {$gte: startDate, $lte: validDate}}, function (err, docs) { ... });
You can store expiration time as UNIX timestamp. In your Mongoose model you can use expiration : { type: Number, required: true}
If you have user interface for creating coupons then you can configure your date picker to send time in UNIX timestamp.
Or If you are getting Date string then you can use var timestamp = new Date('Your_Date_String');
And for calculation of Days you can use Moment JS. Using this you can calculate start of the date using .startOf(); and end of date using .endOf();
Timestamp return from Moment JS can be used for Mongoose query like $gte : some_timestamp and $lte : some_timestamp
If you want to validate the coupon before it is persisted, you can create a max / min value for the date field:
See this sample from official mongoose documentation on DATE validation:
var s = new Schema({ dateto: { type: Date, max: Date('2014-01-01') })
var M = db.model('M', s)
var m = new M({ dateto: Date('2014-12-08') })
m.save(function (err) {
console.error(err) // validator error
m.dateto = Date('2013-12-31');
m.save() // success
})
Hint: use snake_case or camelCase for field names

Nodejs Mongodb Fetch data between date

I have saved my date as timestamp, using the below logic:
var timestamp = Math.floor(new Date().getTime()/1000);
timestamp =145161061
Can any one help me out with the query?
I need to find records between dates and my date is stored in timestamp format as shown above.
If you have specified the type of the field to be date, then even if you store the date by giving the time stamp, it will get stored as Date.
To do a range query on date you can simply do something like this:
db.events.find({"event_date": {
$gte: ISODate("2010-01-01T00:00:00Z"),
$lt: ISODate("2014-01-01T00:00:00Z"),}})
But then if you have specified it as Number, then you can simply do a range query on the number like this :
db.events.find({"event_date": {
$gte: 145161061,
$lt: 145178095,}})
You can try kind of this query:
var startTime = 145161061;
var endTime = 149161061;
Books.find({
created_at: {
$gt: startTime,
$lt: endTime
}
});

Resources