How to query the data with selected date range in CloudBoost - node.js

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 :)

Related

Unable to query between dates in DynamoDB from NodeJS Lambda

I'm having some issues trying to query between dates for a dynamboDB table using NodeJS
I'm trying to query for the data in the data between the dates in the actualReadDate column and get these columns back: meterName, meterNumber, actualReadDate,actualReadTime
I've tried a few different things I've found online, latest attempt is below
async function scanForResults(){
try {
var params = {
TableName: 'MeterReadSubmission-dev',
keyConditionExpression : 'actualReadDate between :from and :to',
ProjectionExpression : 'meterName, meterNumber, actualReadDate,actualReadTime',
ExpressionAttributeValues: {
":from": startDate,
":to": endDate
}
};
var result = await docoClient.query(params).promise()
console.log("Retrieved data: ");
console.log(JSON.stringify(result))
} catch (error) {
console.error(error);
}
}
scanForResults()
The startDate and endDate variables are declared further above with the same format as the dates stored in DynamoDB
I looked at this link: Query DynamoDB between certain dates -NodeJs
But still just can't get it to work. Thanks in advance

Is there any query to find data between given dates?

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

Mongoose: Running Scheduled Job Query by Date

I want to create a scheduled job for patients in a hospital. The patients will be informed every month by their reg_date.
I'm using new Date().getDate() inside my scheduled Jobs to run at 8.00 AM in the morning to send SMS to my patients. Meanwhile, I had been using string format date to save reg_date in my mongoDB. Here is snippets of my mongoDB docs :
{
customer: "John",
reg_date: "2017-02-17T16:39:26.969Z"
}
I've ben surfing for solutions but it turns out nothing, so I decided to post myself. Here is what i am trying to do :
customer.find({"reg_date.getDate()" : new Date(2017, 03, 17).getDate()})
.then(function(data) {
for (var key in data.length) {
sendTheSMS(key[data]);
};
});
E.g: What I am doing is "I want to get every patient who register at 17th day of the month and send them a SMS".
Any help will be appreciated. :D
For this type of bit complex query you need to use aggregation method instead regular find method.
$project this will help you to project your fields, here we are creating a new temporary field day with only date of the reg_date. Then we query using the new field day and we get the result.
This temp field day will never added to your schema or model, it is just like temp view we are creating like in SQL.
Here i projected only customer and day but Please project all the fields necessary in the result.
function getCustomerList(day, callback){
customer.aggregate([
{
$project:{
"customer": "$customer", //repeat the same for all field you want in result
"reg_date": "$reg_date",
"day":{$dayOfMonth:"$reg_date"} //put day of month in 'day'
}
},
{
$match:{
"day": day //now match the day with the incoming day value
}
},
], function(err, result){
callback(err, result);
})
}
getCustomerList(17, function(err, result){ // call the function like this with date you want
// Process the err & result here
});
Result will be like this
[{
"_id" : ObjectId("571f2da8ca97eb10163e6e17"),
"customer" : "John",
"reg_date" : ISODate("2016-04-17T08:58:16.414Z"),
"day" : 17
},
{
"_id" : ObjectId("571f2da8ca97eb10163e6e17"),
"customer" : "Prasanth",
"reg_date" : ISODate("2016-04-17T08:58:16.414Z"),
"day" : 17
}]
Ignore the day field projected during your process...
With reg_date in string you can't query for day of month as it only works with ISODate. I suggest first you convert the string in reg_date in all your documents with a script.
Then the following query should work
customer.aggregate([
{
$project:{
"document": "$$ROOT", //to get the whole document
"day":{$dayOfMonth:"$date"} //put day of month in 'day'
}
},
{
$match:{
"day": 17 //match 17
}
},
], function(data) {
for (var key in data.length) {
sendTheSMS(key[data]);
};
})
Use greater than and less than
var previousDate =new Date(2017, 1, 16); //month starts with 0
var nextDate=new Date(2017, 1, 18);
customer.find({reg_date : { $gt:previousDate,$lt:nextDate}})
.then(function(data) {
for (var key in data.length) {
sendTheSMS(key[data]);
};
});
Since reg_date is stored as a string, and not a Date/ISODate, you're limited as to what kind of query you can run (so I concur with the comment in one of the other answers that you should consider converting them to proper ISODate).
Considering that you want to query a date string for entries with a particular day-of-month, you can use a regular expression query:
customer.find({ reg_date : /-17T/ })
Or, dynamically:
let today = new Date();
let dom = ('00' + today.getDate()).slice(-2); // zero-pad day of month
let re = new RegExp('-' + dom + 'T');
customer.find({ reg_date : re })
You should also read this regarding speed optimizations, but still, regex queries aren't very fast.

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