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());
Related
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.
I am using DatePicker of NativeBase and want to change the format of the displayed date after picking a date. I am unable to find a relevant prop due to lack of docs.
Is there a way I could change the format of the date as in DatePickerAndroid using format="YYYY-MM-DD"?
Fixed in native-base v2.6.1 onwards.
<DatePicker
formatChosenDate={date => {return moment(date).format('YYYY-MM-DD');}}
..... />
Try this:----
async onPressAction() {
try {
const {action, year, month, day} = await DatePickerAndroid.open({
// Use `new Date()` for current date.
// May 25 2020. Month 0 is January.
date: new Date(2018, 6, 26)
});
if (action !== DatePickerAndroid.dismissedAction) {
// Selected year, month (0-11), day
var date = new Date(year, month, day);
var year = date.getFullYear();
var month = date.getMonth()+1;
var day = date.getDate();
console.log('>>>>>>>>>>>>>'+year);
console.log('>>>>>>>>>>>>>'+month);
console.log('>>>>>>>>>>>>>'+day);
console.log(year+'-'+month+'-'+day);
}
} catch ({code, message}) {
console.warn('Cannot open date picker', message);
}
}
I have my birthDate in string format like this "2010-03-22". I want to convert it in the Date type in MongoDB.
What db.patient.update() function should I write ?
I want to calculate the age of each person.
I used the solution give on How do I convert a property in MongoDB from text to date type? but all the dates got converted to "1970-01-01T00:00:00.000Z".
db.collection.find().forEach(function(e){
e.fieldname = new Date(e.fieldname)
db.collection.save(e)
});
If you are using robomonogo use new ISODate instead of new Date
One approach you could take in converting the field to the correct date object would be by splitting the string on the given delimiter "-". Use parseInt() to convert the delimited strings into numbers, and the new Date() constructor builds a Date from those parts: the first part will be the year, the second part the month, and the last part the day. Since Date uses zero-based month numbers you have to subtract one from the month number.
The following demonstrates this approach:
var cursor = db.patient.find({"birthDate": {"$exists": true, "$type": 2 }});
while (cursor.hasNext()) {
var doc = cursor.next();
var parts = doc.birthDate.split("-");
var dt = new Date(
parseInt(parts[0], 10), // year
parseInt(parts[1], 10) - 1, // month
parseInt(parts[2], 10) // day
);
db.patient.update(
{"_id": doc._id},
{"$set": {"birthDate": dt}}
)
};
For improved performance especially when dealing with large collections, take advantage of using the Bulk API for bulk updates as you will be sending the operations to the server in batches of say 500 which gives you a better performance as you are not sending every request to the server, just once in every 500 requests.
The following demonstrates this approach, the first example uses the Bulk API available in MongoDB versions >= 2.6 and < 3.2. It updates all
the documents in the collection by changing the OrderDate fields to date fields:
var bulk = db.patient.initializeUnorderedBulkOp(),
counter = 0;
db.patient.find({"birthDate": {"$exists": true, "$type": 2 }}).forEach(function (doc) {
var parts = doc.birthDate.split("-");
var dt = new Date(
parseInt(parts[0], 10), // year
parseInt(parts[1], 10) - 1, // month
parseInt(parts[2], 10) // day
);
bulk.find({ "_id": doc._id }).updateOne({
"$set": { "birthDate": dt}
});
counter++;
if (counter % 500 == 0) {
bulk.execute(); // Execute per 500 operations and re-initialize every 500 update statements
bulk = db.patient.initializeUnorderedBulkOp();
}
})
// Clean up remaining operations in queue
if (counter % 500 != 0) { bulk.execute(); }
The next example applies to the new MongoDB version 3.2 which has since deprecated the Bulk API and provided a newer set of apis using bulkWrite():
var bulkOps = db.patient.find({"birthDate": {"$exists": true, "$type": 2 }}).map(function (doc) {
var parts = doc.birthDate.split("-");
var dt = new Date(
parseInt(parts[0], 10), // year
parseInt(parts[1], 10) - 1, // month
parseInt(parts[2], 10) // day
);
return {
"updateOne": {
"filter": { "_id": doc._id } ,
"update": { "$set": { "birthDate": dt } }
}
};
})
db.patient.bulkWrite(bulkOps);
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 }.