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}});
Related
How do I save a timestamp value to firestore using cloud functions.
I tried this (adding 30 days to the timestamp) but it ends up saving the value as a number
var now = new Date();
await docRef.update({
'subscription':{
package:req.query.package,
endDate: now.setTime(now.getTime()+(30 *24+60+60+1000))
}
})
If you want to add days to the date, then you should setDate() instead. By using setTime() you're setting the time instead of the date. See code below:
var now = new Date();
now.setDate(now.getDate() + 30);
await docRef.update({
'subscription':{
package: req.query.package,
endDate: now
}
})
For more information, you should check out this documentations:
Date.prototype.setDate()
Date.prototype.getDate()
I'm creating a mongo database which stores array of objects of the following form
{
_id: 5ca37dc35b55092ab2b0980e,
driverID: 'cjttwclbr00ui0714y2dodxe2',
createdAt: 2019-04-02T15:20:35.021Z,
updatedAt: 2019-04-02T15:20:35.021Z, __v: 0
}
I want to filter those results which belongs to a particular driver based on the day and hour
eg: I want to get all the records which created on 2nd hour of today which belongs to a particular driver
How can I write find query or aggregation method based on this scenario?
I can get hour of the day using
const hour = new Date().getHours();
To get all the driver data b/w a particular hour
var date = new Date(); // for today
date.setHours(n,0,0,0); // n is the hour
var endHour = new Date();
endHour.setHours(n+1,0,0,0);
var query = {
driverID:driverId,
createdAt :{ $gte:date,$lt:endHour}
}
db.collection.find(query);
I have a MongoDB model that contains a Date field whose type is defined as Date.now. Any date is converted to ISO date format. Inside the model the date is defined as :
xDate : {
type: Date.now,
required: true
}
I pass the current Date as :
var d = new Date();
var temp = d.toISOString();
var subStr = temp.substr(10,temp.length - 1);
var curDate = temp.replace(subStr, "T00:00:00.000Z");
console.log(curDate);
However the date is stored as an ISO String inside the MongoDB schema. I try to query it using Mongoose using the following query:
X.
find({
xDate: curDate
})
.exec(function(err, doc) {
var response = {
status : 200,
message : doc
};
if (err) {
console.log('Error');
response.status = 500;
response.message = err;
} else if (!doc) {
console.log("Documents against the date not found in database" ,curDate);
response.status = 404;
response.message = {
"message" : "Documents not found for " + curDate
};
}
res
.status(response.status)
.json(response.message);
});
I keep getting a blank json array inspite of the data being there. Inside the table the xDate is stored as YYYY-MM-DD format.
The date inside mongo is not stores in ISO string. If you save your model as Date.now, it will save a new Date object, not an ISO string. So one easy way of querying is to query by new Date() object.
Also note that your query is hard to be true, since you will have a hard time getting the exactly same date as your data is stored. I think better option for you is using $lt or $gt filters.
New query should look something like:
let currDate = new Date()
// change the date using class methods
X.find({
xDate: {$lt: currDate}
}).exec...
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);
})
})
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 }.