Passing dynamic value gets failed in Mongodb using java script - mongodb

I have to copy the data from one collection to another collection based on a date. Here date is calculated as yesterday date dynamically and working properly.
If i pass the dynamic date value as /$yesterday/ to mongo find method, Its getting failed.
Assume data_timestamp format is 2013-08-20 17:04:40.633 and trying to get the result by like query.
Sample JS Code:
db=db.getSiblingDB('masterdb')
$today = new Date();
$yesterday = new Date($today);
$yesterday.setDate($today.getDate() - 1);
var $dd = $yesterday.getDate();
var $mm = $yesterday.getMonth()+1;
var $yyyy = $yesterday.getFullYear();
if($dd<10){$dd='0'+dd} if($mm<10){$mm='0'+$mm} $yesterday = $yyyy+'-'+$mm+'-'+$dd;
db.mastercollection.find( { "data_timestamp": /$yesterday/ } ).forEach( function(x){db.newcollection.insert(x)} );
Is any other way to pass dynamic value without using '$' symbol?
Please share your valuable comments
Thanks in advance...
Ramesh Kasi

The way you're doing your query now, I'm pretty sure that /$yesterday/ is being interpreted as a regular expression matching strings starting with "yesterday". A better approach would be to use the $regex operator so that you can pass in a javascript variable that holds the regular expression you hope to match.

Related

Conditional formatting for dates

I'm trying to come up with a simple conditional format formula for highlighting cells that have a date that is greater than three months older than today's date. It seems though that the "Date is before" option only gives a few options, none of them seem to allow what I'm looking for. Is there a custom formula that could accomplish this?
Edit: attaching a snip of the column in question:
Formula :
=DAYS(now(),B2)>90
Go to the custom formula in the conditional formating rules and use this:
=DATEDIF(A1,TODAY(),"D")<90
try:
=1*C2>DATE(YEAR(TODAY()), MONTH(TODAY())+3, DAY(TODAY()))
also make sure you have valid dates and not plain text dates. you can test this with ISDATE formula
You can use Apps Script and a Custom Menu in order to solve your issue with setting the color in the cell depending on the date. Go to Tools->Script Editor and paste this code:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Custom Menu')
.addItem('Check Difference', 'dateDifference')
.addToUi();
}
function dateDifference(){
var sheet = SpreadsheetApp.getActiveSheet().getActiveRange(); // Get the selected range on the sheet
var dates = sheet.getValues(); // Get the values in the selected range
var oneDay = 1000*60*60*24;
var row = 1;
var re = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/; // This will help you to check if it's really a date
dates.forEach(function(el){ // Iterate over each value
if(typeof el[0] == 'object'){ // Check if it's really a date
var gmtZone = el[0].toString().split(" ")[4].split(":")[0]; // Take the date's GMT
var dateFormatted = Utilities.formatDate(el[0], gmtZone, "dd/MM/yyyy"); // Format the date
if(re.test(dateFormatted)){ // Test if it's the right format
// This part will calculate the difference between the current date and the future date
var futureDateMs = new Date(el[0]);
var todayDateMs = (new Date()).getTime();
var differenceInMs = futureDateMs - todayDateMs;
var differenceInDays = Math.round(differenceInMs/oneDay);
if(differenceInDays >= 91.2501){ // Test if the difference it's greater to 91.2501 days (3 motnhs)
sheet.getCell(row, 1).setBackground("#00FF00"); // Set the color to the cell
}
row++;
}
}
});
Save it by clicking on File->Save.
Then you can select a range in a column and click on Custom Menu->Check Difference as you can see in the next image:
As you can see, you will get the desired result:
Notice
It's really important to be careful with what you consider to be a "month", I mean how many days you are going to take into consideration. In my code, I took Google's suggestion of 1 = 30.4167.
Docs
These are other Docs I read to be able to help you:
Utilities.formatDate()
Working with Dates and Times.
I hope this approach can help you.

Add day to date with momentjs

I am trying to add a day to my date:
let createdDate = moment(new Date()).utc().format();
let expirationDate = moment(createdDate).add(1, 'd');
console.log(expirationDate);
However, this keeps returning an obscure object {_i: "2017-12-20T21:06:21+00:00", _f: "YYYY-MM-DDTHH:mm:ss Z", _l: undefined, _isUTC: false, _a: Array(7), …}
fiddle:
http://jsfiddle.net/rLjQx/4982/
Does anyone know what I might be doing wrong?
You are logging a moment object. As the Internal Properties guide states:
To print out the value of a Moment, use .format(), .toString() or .toISOString().
let createdDate = moment(new Date()).utc().format();
let expirationDate = moment(createdDate).add(1, 'd');
console.log(expirationDate.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
Please note that you can get the current date using moment() (no need to use new Date()) or moment.utc().
I will go with this one, simple works for me and I don't think you need other function to only add day in moment.
var yourPreviousDate = new Date();
var yourExpectedDate = moment(yourPreviousDate).add(1, 'd')._d;
The add method modifies the moment object. So when you log it, you're not getting an obscure object, you're getting the moment object you're working with. Are you expecting a formatted date? Then use format or some other method.
I agree with other answers just providing shortcut and different ways
You can do the format at the same time
moment().add(1,'d').format('YYYY-MM-DD');
or you can just format any date or date object
moment(result.StartDate).format('YYYY-MM-DD');

How to return a normal javascript date object?

Is it possible to return a javascript date object from this? I have an text input field with the calendar and want to return a standard date object from it's value... Is this possible?
Is this what you are looking for?
var date = '2016-06-12'; // Can be document.getElementById('myField').value that points to your date field.
var date_parts = date.split('-');
var date_obj = new Date(date_parts[0],date_parts[1],date_parts[2]);
console.log(date_obj);
You can also simply use
new Date(document.getElementById('myField').value)
and see if it works. The date function is smart enough to parse based on browser's locale. This should work for time as well. Eg. new Date('2016-06-12 04:15:30')

jayData complex filter evaluation

I am new to jayData and am trying to filter on an entity set. The filter needs to perform an complex evaluation beyond what I saw in the samples.
Here is a working sample of what I am trying to accomplish (the listView line isn't and is just there to show what I plan to do with the data):
function () {
var weekday = moment().isoWeekday()-1;
console.log(weekday);
var de = leagueDB.DailyEvents.toArray(function (events) {
console.log(events);
var filtered = [];
for (var e = 0; e < events.length;e++) {
console.log(events[e]);
console.log(events[e].RecurrenceRule);
var rule = RRule.fromString(events[e].RecurrenceRule);
var ruleOptions = rule.options.byweekday;
var isDay = ruleOptions.indexOf(weekday);
console.log(ruleOptions, isDay);
if(isDay =! -1)
{
filtered.push(events[e]);
}
}
$("#listView").kendoListView({dataSource:filtered});
});
Basically it is just evaluating a recurring rule string to see if the current day meets that criteria, if so add that event to the list for viewing.
But it blows up when I try to do this:
eventListLocal:leagueDB.DailyEvents.filter(function(e){
console.log("The Weekday is:"+viewModel.weekday);
console.log(e);
console.log("The recurrence rule is:"+e.RecurrenceRule);
var rruleOptions = viewModel.rruleOptions(e.RecurrenceRule);
if (rruleOptions !== -1) {
return true;
}
}).asKendoDataSource()
The error that is generating is:
Exception: Unable to resolve type:undefined
The thing is it seems to be occurring on "e" and the console logs like the event is not being passed in. However, I am not seeing a list either. In short I am really confused as to what is going on.
Any help would be appreciated.
Thanks,
You can't write filter expressions such as this.
When you write .filter(...), jaydata will parse your expression and then it will generate filter for underlying provider, for example where for webSql and $filter for oDataProvider.
Both JayData expression parser and the data provider itself should understand your filter.
Your filter is not suitable for this approach, because most of your codes are not familiar for jaydata expression parser and the underlying data provider, for example your console.log etc.
You can simplify your filter, or you should load all your data into an array, and then you can use filter method of array itself, there, you can write any filter you like, and your filter will work. Of course this has performance issue in some scenarios when your data set is large.
Read more on http://jaydata.org/tutorials/entityexpressions-the-heart-of-jaydata

Grails matching dates

I have a string which is:
"may 2013"
This refers to the second of May. I am trying to get all instances of PostOrder where the date is the second of May.
What I have tried so far:
def t = new Date(new Integer(sp[1]), new Integer(month), 01)
def results = PostOrder.createCriteria().list() {
ilike('dateCreated', t )
}
Please note I have split the string so sp[1] is 2013 and I have parsed the May so the month variable is not 05.
The above attempt does not work.
The only way I know will work is grabbing all objects and doing a for each on them. parsing the dateCreated to a string then doing a .contains(). But this will get very slow and messy.
First point. According to the documentation, ilike() is a case-insensitive 'like' expression - see SQL LIKE Operator. So, it cannot accept a date. What you need is just eq().
def t = new Date(new Integer(sp[1]), new Integer(month), 1)
def results = PostOrder.createCriteria().list() {
eq('dateCreated', t)
}
Another point. The constructor Date() accepts the year minus 1900 as the first argument. So, you probably need to subtract 1900 from new Integer(sp[1]).
Also, that constructor is deprecated; I would suggest to use GregorianCalendar(new Integer(sp[1]), new Integer(month), 1).time.