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);
})
})
Related
i have a problem with mongoDB, im trying to create trigger, that will take server date and compare it with property DueDate and if the DueTime is lesser or equal of the server time, it should swap property borrowed to false.
Problem is that it didnt work and im so lost i tried everything.
There is my trigger function:
exports = function(changeEvent) {
const mongo = context.services.get("MongoDB");
const now = new Date();
const booksLended = mongo.db("test").collection("bookslendeds");
var filter = {DueDate: {$lt: now.toISOString()}, Borrowed: true};
var update = {$set: {Borrowed: false}};
console.log(JSON.stringify(filter));
console.log(JSON.stringify(update));
return booksLended.updateMany(filter, update);
};
This is a console logs:
> ran on Wed Jan 18 2023 23:48:10 GMT+0100 (Central European Standard Time)
> took 524.689137ms
> logs:
{"DueDate":{"$lt":"2023-01-18T22:48:11.778Z"},"Borrowed":true}
{"$set":{"Borrowed":false}}
> result:
{
"matchedCount": {
"$numberInt": "0"
},
"modifiedCount": {
"$numberInt": "0"
}
}
> result (JavaScript):
EJSON.parse('{"matchedCount":{"$numberInt":"0"},"modifiedCount":{"$numberInt":"0"}}')
DataModel
The datatype of the DueDate field is probably UTC datetime, while .toISOString() is returning a string. MongoDB query operators are type-sensitive, so these will not match.
Instead, use the date object directly in the query, like:
var filter = {DueDate: {$lt: now}, Borrowed: true};
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...
This Meteor server code tries to count all the records which are 4 months and newer with property size:'4', color:'white' but account all entires from any one user as one count, so no mater how many documents have been entered by the same user, the are all counted as one. but I am getting nothing in return. any ideas? thx
let date = new Date();
date.setMonth(date.getMonth() - 4);
let doc = UsageCol.aggregate([{
$match: {
createdAt: {
$gte: date,
$lte: new Date()
},
action: 'failBroadcast',
plate: plate
}
}, {
$group: {
_id: {
userId: "$userId"
},
count: {
$sum: 1
}
}
}]);
for (var i = 0; i < doc.length; i++) {
var obj = doc[i];
console.log(JSON.stringify(obj));
}
Alright I just wanted to clear some things up from this morning.
The only reason I recommended moment js was thinking we are storing the date in date type and there is no easy way to dynamically create date in UTC using java script date function
So now that we know you used Date.now() to save the dates, you don't need any moment js.
The correct syntax is
let dateToMillis = Date.now(); //The current millis from epoch.
let dateFrom = new Date(dateToMillis); // Use the current millis from epoch.
let dateFromMillis = dateFrom.setMonth(dateFrom.getMonth() - 4); // The millis 4 months ago from epoch.
Pass dateToMillis and dateFromMillis to aggregation query.
I have a DynamoDB and some items there have a date field. The date field is a string of the format {YYYY-MM-DD}. What should I have to write that the DB will retrieve all items which date field is between a start date and an end date?
This is my code:
function searchFile(from_date, until_date) {
AWS.config = new AWS.Config({accessKeyId: '***', secretAccessKey: '***', region: '***'});
var dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});
var params = {
"TableName" : '***',
FilterExpression: "Date_ = :date",
ExpressionAttributeValues: {
// What should I write here?
},
}
dynamodb.scan(params, function(err,data) {
if (err) {
console.log(err);
}
console.log(data);
})
}
The DynamoDB stores dates as String. You can use BETWEEN operator to get the range of dates.
createdate - is the attribute name
FilterExpression: "createdate BETWEEN :date1 and :date2",
ExpressionAttributeValues: {
":date1": "2010-05-05",
":date2": "2011-10-04",
}
Date S (string type). The Date values are stored as ISO-8601 formatted
strings.
BETWEEN : Greater than or equal to the first value, and less than or
equal to the second value.
I'm hard-coding some dates to write back to a model.
E.g.
oEntry.StartDate = "2016-03-28T00:00:00";
This is throwing out an invalid date error on:
oModel.create("/CalendarSet", oEntry, {
success : success,
error : error
});
What is the correct format for the date?
You can just use the Javascript Date element.
oEntry = {
StartDate: new Date(year, month, day, hours, minutes, seconds, milliseconds)
};
oModel.create("/CalendarSet", oEntry, {
success : success,
error : error
});
Source:MDN
If you need it for the sPath in the URL you can use following to get a DateTime String.
getTimestamp: function getTimestamp(oDate){ //TODO: JsDoc
this.oLogger.info("Enterd function Timestamp(oDate)");
return sap.ui.core.format.DateFormat.getDateTimeInstance({pattern : "yyyy-MM-ddTKK:mm:ss"}).format(oDate || new Date());
},
This is what you need:
oEntry = {};
oEntry.StartDate = new Date(); // assuming "StartDate" is corr. fieldname in your service
// also assuming its the only key in your entity
// and its type DateTime
oModel.create("/CalendarSet", oEntry, {
success : success,
error : error
});