How to make a query using dates - mongodb

I need to pull from the DB all rows in a day
var i_sDate = "2014-06-21"; // (user input)
var startDate = new Date();
var month = parseInt(i_sDate.substr(5,2)) - 1;
var day = i_sDate.substr(8,2);
startDate.setFullYear(i_sDate.substr(0,4), month, day);
startDate.setHours(0, 0, 0, 0);
var endDate = new Date();
endDate.setFullYear(i_sDate.substr(0,4), month, day);
endDate.setHours(23, 59, 59, 0);
var query = {start_time:{"$gte": "ISODate('" + startDate.toISOString() + "')", "$lt": "ISODate('" + endDate.toISOString() + "')"}};
var tableInfo = Users_Collection.find(query).fetch();
console.log(query);
when I print "query" it looks OK, but I don't get any result at all, I put the same information directly on the DB and I get the expected result. It seems like I'm building the query in the wrong way, any suggestion?????
thanks in advance!

You should directly use Date objects in your query. Try this:
var query = {start_time: {$gte: startDate, $lt: endDate}};
It also looks like you were missing a closing }.

Related

Fetch MongoDb Documents whose timestamp is today

I have a mongodb model whose creation date is stored in milliseconds(epoch time). I want to fetch only documents whose milliseconds matches today.
So, here is what I'm trying to achieve:
let query = {"pick_up_time":12262672627271}; // I want this to translate to pick_up_time is today
Is it possible to apply a transformation function to this?
I have this function to check if requested date is today
function isToday(someDate) {
const today = new Date()
return someDate.getDate() == today.getDate() &&
someDate.getMonth() == today.getMonth() &&
someDate.getFullYear() == today.getFullYear()
}
So, that my query will now be
let query = {"pick_up_time":isToday(12262672627271)};
How can something like this be achieved with mongodb?
I think this function can help you to create dynamic queries for each day
const getTimeQuery = () => {
const now = new Date();
const year = now.getFullYear();
const month = now.getMonth();
const day = now.getDate();
const startDate = new Date(year, month, day, 0, 0, 0).getTime();
const endDate = new Date(year, month, day, 24, 0, 0).getTime();
const query = {
"pick_up_time": { $gte: startDate, $lte: endDate }
}
return query
}
console.log(getTimeQuery());

How to compare two dates with Mongodb (find query using NestJS)

I'm trying to get the list of posts for which the publish date is equal or less than the current date.
I'm using NestJS, Mongo & typeORM; which syntax should I use?
const posts =
await this.mbRepository.find(
{ where: { "deletedAt": null , "publishDate" <= currentDate } }
);
let firstPoint = new Date();
firstPoint.setHours(0);
firstPoint.setMinutes(0);
firstPoint.setSeconds(0);
let lastPoint = new Date();
lastPoint.setHours(23);
lastPoint.setMinutes(59);
lastPoint.setSeconds(59);
const posts = await this.mbRepository.find({ publishDate: { $gte: firstPoint, $lt: lastPoint } } });
Get current day and make two point. One as begining of the day and another as end of the day. Then you can use mongodb operator $gte and $lt. In this way you will get all post which have been publish in this time range.

Mongodb get data using ISO format date

I am saving data into mongodb and the dates are in this format for instance
7/30/1960 (july 30, 1960) is ISODate("1960-07-30T05:00:00.000+0000"),
I want to find records created today(and i dont care about the time,so long as its today) and i have this
var start = new Date();
var end = new Date();
and to display the data
db.posts.find({created_on: {$gte: start, $lt: end}});
Will this work or must i convert my iso dates to another format first?.
You can alter the 'start' and 'end' variables before querying:
var start = new Date();
start.setHours(0,0,0,0); // remove time part from the date
var end = new Date();
end.setHours(0,0,0,0); // remove time
end.setDate(end.getDate() + 1); // add a day to the end date
and then you can use your query:
db.posts.find({created_on: {$gte: start, $lt: end}});

Compare date (moment.js) in MongoDB

I want to compare date from MongoDB and my date.
Also i read this and this post and I did not find an answer.
My Code :
today: function() {
var today = moment().format();
return Posts.find({createdAt : { $gte : today}}) // show posts created in "future" , so this function must return nothing
},
createdAt = moment().format();// in MongoDB
As a result this construction doesn't work, but if i compare lie this :
var today = moment().format();
var daystart = moment().startOf('day').format();
if (daystart > today){
console.log ("YES");
}
else if (daystart < today)console.log ("NO");
Return
"NO"
Anybody help ?
EDIT :
today: function() {
var today = moment().toDate();
var daystart = moment().startOf('day').toDate();
// console.log(today + daystart);
return Posts.find({createdAt : { $gt : today}})
},
week: function() {
var today = new Date();
return Posts.find({createdAt : { $lt : today}})
},
month: function() {
var today = new Date();
return Posts.find({createdAt : { $ne : today}})
}
createdAt = new Date();
The .format() method is a display helper function which returns the date string representation based on the passed token argument. To compare the date from MongoDB with the the current date and time, just call moment() with no parameters, without the .format() method and get the native Date object that Moment.js wraps by calling the toDate() method:
today: function() {
var now = moment().toDate();
return Posts.find({createdAt : { $gte : now }});
}
Convert date to MongoDB ISODate format in JavaScript using Moment JS
MongoDB uses ISODate as their primary date type. If you want to insert a date object into a MongoDB collection, you can use the Date() shell method.
You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats:
new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.
new Date("<YYYY-mm-ddTHH:MM:ss>") specifies the datetime in the client’s local timezone and returns the ISODate with the specified datetime in UTC.
new Date("<YYYY-mm-ddTHH:MM:ssZ>") specifies the datetime in UTC and returns the ISODate with the specified datetime in UTC.
new Date() specifies the datetime as milliseconds since the Unix epoch (Jan 1, 1970), and returns the resulting ISODate instance.
If you are writing code in JavaScript and if you want to pass a JavaScript date object and use it with MongoDB client, the first thing you do is convert JavaScript date to MongoDB date format (ISODate). Here’s how you do it.
var today = moment(new Date()).format('YYYY-MM-DD[T00:00:00.000Z]');
console.log("Next day -- " + (reqDate.getDate() + 1))
var d = new Date();
d.setDate(reqDate.getDate() + 1);
var tomorrow = moment(d).format('YYYY-MM-DD[T00:00:00.000Z]');
You can pass today and tomorrow object to MongoDB queries with new Date() shell method.
MongoClient.connect(con, function (err, db) {
if (err) throw err
db.collection('orders').find({ "order_id": store_id, "orderDate": {
"$gte": new Date(today), "$lt": new Date(tomorrow)}
}).toArray(function (err, result) {
console.log(result);
if (err) throw err
res.send(result);
})
})

Date Filter in sapui5

I have used two date controls to filter a row repeater as,
oF_cell5 = new sap.ui.commons.layout.MatrixLayoutCell({id:"F05",colSpan : 2});
var oCreateFrom = new sap.ui.commons.DatePicker("EV_AE_DATE1",
{width:"150px",placeholder:"Created From",
change:function(oEvent){
oController.onChangeFilterValue(oEvent);}
})
oF_cell51 = new sap.ui.commons.layout.MatrixLayoutCell({id:"F051",colSpan : 2});
var oCreateTill = new sap.ui.commons.DatePicker("EV_AE_DATE2",
{width:"150px",placeholder:"Created Till",
change:function(oEvent){
oController.onChangeFilterValue(oEvent);}
});
Now i have a rowrepeater in which one of the column is CreatedOn date like..,,
new sap.m.HBox({
items:[new sap.ui.commons.TextView({text:"Created on:"}),
new sap.ui.commons.TextView("TV11")
.bindProperty("text",
{
path: "CM_EventList>CREATEDON",
type: new sap.ui.model.type.Date({pattern:"MMM dd, yyyy",
source : {pattern : "dd.MM.yyyy"}})
})]
}),
And in the controller i have written this code as....,,
onInit: function() {
var model = new sap.ui.model.json.JSONModel("eventlist.json");
model.setData();
sap.ui.getCore().setModel(model,"CM_EventList");
},
onChangeCmFilterValue : function(oEvent){
var CM_FDATEVAL = sap.ui.getCore().byId("EV_AE_DATE1").getValue();
var CM_TDATEVAL = sap.ui.getCore().byId("EV_AE_DATE2").getValue();
var CM_Date = new sap.ui.model.Filter('CM_EventList>CREATEDON',
sap.ui.model.FilterOperator.BT,CM_FDATEVAL,CM_TDATEVAL);
var oCM_VBOX1 = sap.ui.getCore().byId("EV_CM_VBOX");
var oCM_RR1 = sap.ui.getCore().byId("EV_AE_ROWREPEATER");
oCM_RR1.bindRows('CM_EventList>/eventlist',oCM_VBOX1,null,[CM_Date]);
},
And the eventlist is my seperate json file which has date values as
{
"eventlist": [
{
"CREATEDON": "10.07.2014",
},
{
"CREATEDON": "10.08.2014",
},
.......
and so on..........
Now if select a date range from my date controls then the row repeater should show the records which are between the range of dates as in my json.
But the filter is not working.
Please Help me on this.
Thanks
Sathish
First of all, use the DatePicker Control for date fields in your view if you aren't using it already.
You can obtain the value of your date picker as a Date object using the method GetDateValue(). You can then use these date objects to create a filter for a datetime field of your data model.
var dateFrom = this.getView().byId("filterDateFrom").getDateValue();
var dateTo = this.getView().byId("filterDateTo").getDateValue();
if (dateFrom != null && dateTo != null) {
filter = new sap.ui.model.Filter(
"CM_EventList>CREATEDON",
sap.ui.model.FilterOperator.BT,
dateFrom,
dateTo
);
}
By the way: Note that both date objects will actually represent the moment at the beginning of the day (0:00:00) while the timestamps in your database will often be some point in time throughout the day. So when you want to search between two dates inclusively, you need to add one day to dateTo:
dateTo.setDate(dateTo.getDate() + 1);
Another problem you might or might not have to deal with are timezones... and of course all the other falsehoods programmers believe about time.
I think you should check the value of the following. The format should be different than your json value "CREATEDON": "10.08.2014".
var CM_FDATEVAL = sap.ui.getCore().byId("EV_AE_DATE1").getValue();
var CM_TDATEVAL = sap.ui.getCore().byId("EV_AE_DATE2").getValue();
Please try create a DatePicker with:
type: new sap.ui.model.type.Date({pattern: ""yyyy-MM-dd""})
Edit: to use Date as filter
var CM_FDATEVAL_DATE = new Date(sap.ui.getCore().byId("EV_AE_DATE1").getValue());
var CM_TDATEVAL_DATE = new Date(sap.ui.getCore().byId("EV_AE_DATE2").getValue());
Regards,
Allen