I'm writing a mongo query to show records based on the current time. However, the query returns 0 records when I try to query against date and time. Below is the query:
let now = momenttz.tz(moment(),tz).toDate();
tmpl.listSelectorFilter('scheduledVisits', {
$gte: now,
$lte: moment.utc(today, 'MM/DD/YYYY').endOf('week').toDate()
});
Note: If I set the time to zero hours, it works.
How do I change this query in order to make it work? Any help is appreciated.
Does the data you're querying against have timestamps or a dateTime object to compare? Essentially you aren't comparing the records to any time, so there is no way for mongo to know what to filter by.
I would suggest you do something like a find instead and compare to dates within the record with the appropriate date field:
example:
db.collection.find({
{ $and: [ { data.date: { $gte: now } }, { data.date: { $lte: endOfWeek } } ] }
})
also keep in mind that in mongo land you can't use functions like you would do with moment, hence why I put "endOfWeek" which would be a variable you set similar to now:
let now = momenttz.tz(moment(),tz).toDate();
let endOfWeek = moment.utc(today, 'MM/DD/YYYY').endOf('week').toDate()
Related
Maybe this subject often question to ask, but I not find what I want it.
I have a collection with keys and values like this:
{
_id: ObjectId("6142f3a47245125aef7ffcc0"),
addTime: '2021-09-16 14:35:00',
editTime: '2021-09-16 14:35:00'
}
I want to dump before August 2021. What syntax do I have to use?
I trying in roboT and mongo shell, before dump I try find first.
db.collections.find({addTime:{$lte:new Date("2021-09-01")}})
and the result is
Fetched 0 record(s) in 3714ms
You can make use of the $expr operator to temporarily convert the string to a date-time value and then perform your query.
db.collection.find({
"$expr": {
"$lte": [
{
"$dateFromString": {
"dateString": "$addTime",
"format": "%Y-%m-%d %H:%M:%S", // <- Your date time format in string
"onNull": new Date("9999-09-01"), // <- Default calue if query key doesnt exist (Dont modify this value, unless required)
}
},
new Date("2021-09-01"), // <- Your datetime query value (can also be `ISODate` format)
],
}
})
Mongo Playground Sample Execution
Because GraphQL doesn't use the DateTime scalar, I have decided to convert all the fields in my MongoDB database collections that are of the type, DateTime, into Integer, representing DateTime as milliseconds. I have about 8,000+ documents that need to be modified and created a script to do the work.
The script was supposed to create a new field "publishedID", Integer scalar, to correspond with the "published" field. When I loaded my script, all the documents were over written, leaving only the DateTime field - although, as I intended, in milliseconds - but all the other fields, such as, "title", "image", "body", "subtitle", including other DateTime types like, "modified" and "created", etc. were deleted.
Below is the script I ran:
db.Post.find().forEach(function(myDoc) {
let currentDate = new Date(myDoc.published);
print(currentDate);
db.Post.update(
{ published: currentDate },
{ publishedID: currentDate.valueOf() }
);
});
I had hoped the ISO DateTimes, previously set for the "published" field would just have been converted to milliseconds, I got that. But I did not want everything else in the document deleted.
Here, you are missing the $set operator in the update query which is the root cause of all fields deletion in the documents
db.Post.find().forEach(function(myDoc) {
let currentDate = new Date(myDoc.published);
print(currentDate);
db.Post.update(
{ published: currentDate },
{ $set: {publishedID: currentDate.valueOf()} } // $set: {} added
);
});
$set operator updates the given fields but here we have added one field only which will replace the existing fields in the matched collections.
I'm using the Bookshelf.js ORM and I need be able to query by date and having some issues.
here is a samples code snippet that I'm using.
this.model.query((q) => {
q.where('created_at', '>=', Date.now());
q.orderBy('created_at', 'DESC');
})
.fetch().then(function (model) {
socket.send(JSON.stringify(model));
});
The above code just returns a null or empty array.
Any ideas?
It is really a pity your query returns empty results, querying in the future is a very nifty feature to have.
But I think you want data created in the past, right? So try
this.model.query((q) => {
q.where('created_at', '<=', new Date());
q.orderBy('created_at', 'DESC');
})
.fetch().then(function (model) {
socket.send(JSON.stringify(model));
});
Note also Date.now() that gives the milliseconds elapsed since the UNIX epoch was replaced by new Date() that gives the proper current date/time.
Anyway, the criteria makes not much sense either because it basically means all rows. Unless, of course, you are looking after some bug on created_at column or filtering out NULL attributes.
I have a collection of activities and MongoDB. Activities also have a date. I'm trying to dynamically build a table with all activities saved in my collection. Therefor I want to change the format of the date with moment.js right before I send the array of JSON objects to my jade file.
I tried to make a new results array and send this one over to my jade file.
router.get('/', function(req, res, next) {
activitiesController.getActivities(function(results) {
if(!results) {
results = [];
}
for(var key in results) {
results[key].date = moment(results[key].date).format('ddd, hA');
}
res.render('index', {
activities: results
})
});
});
This is how the results array looks:
[{
"_id" : ObjectId("56fe2c0d7afcafa412ae19c2"),
"title" : "Fitnessstudios",
"category" : "Sport",
"time" : 2,
"date" : ISODate("2016-03-30T00:00:00.000Z"),
"__v" : 0
}]
Your problem is that the value you are passing to moment.js is:
ISODate("2016-03-30T00:00:00.000Z")
when it wants just the date string part:
"2016-03-30T00:00:00.000Z"
So get just the date string and pass that, the snippet below shows how to do that.
var dateString = 'ISODate("2016-03-30T00:00:00.000Z")'.replace(/^[^\"]+\"([^\"]+)\".*$/,'$1');
document.write(dateString);
moment.js will likely parse an ISO string just fine without further help, however I think it's much better to tell it the format, so you should use something like:
var dateString = results[key].date.replace(/^[^\"]+\"([^\"]+)\".*$/,'$1');
results[key].date = moment(dateString,'YYYY-MM-DDThh:mm:ss.sssZ').format('ddd, hA');
// Wed, 10AM
And you should not use for..in over an array, you may find properties other than those you expect and in a different order. Use a plain for, while or do loop or one of the looping methods like forEach, map, etc. as appropriate.
Change this:
moment(results[key].date).format('ddd, hA');
to
moment(new Date(results[key].date.toString()),moment.ISO_8601).format('ddd, hA');
I am trying to query a collection in Mongo database, to get all record with Time field in a date range. Time is defined as Date in database.
My environment: Node.js, Express, Jade, javascript.
This is the javascript code:
var query = {};
var timeQuery = {};
timeQuery["$lt"] = new Date().toISOString();
query["Time"] = timeQuery;
console.log(query);
db.model('testruns').find(query).exec(function (err, testruns) {
console.log(testruns.length);
// doing something
});
the result printed to console:
{ Time: { '$lt': '2014-10-30T15:04:39.256Z' } }
0
The query returns 0 results (there should be more)
By the way... Running date queries from RoboMongo returns results, just the wrong ones. for example:
db.testruns.find({Time : {"$gte" : new Date("2014-10-30T15:13:37.199Z")}})
returns all records.
What I tried:
This one, that one, another one, mongoose documentation of course, and many more results from google.
Most of them give the same answer, none of them works for me. HELP!
as far I see you are not including the field to reference in the query, can you try this:
I assume your field name is 'time'
var date = new Date(); //or the date you want to compare
db.model('testruns').find({"Time":{"$lt":date}}).exec(function (err, testruns) {
console.log(testruns.length);
// doing something
});
The problem was related to a schema definition, not directly to this code. The code of the query was correct. a schema definition had this field(Time) as String, which caused MongoDB to try and find a string in a date field...