Getting Mongo results from one month ago - mongodb

I have around 30-40 records like the example before in my database and I'm looking to get the notifications that are less than 1 month old (from today's date). Is there a way in Mongo to get these results without having to pass in a today's date via JavaScript? Or if I do have to pass it in via JavaScript, how would I process this against my created date?
{
"_id" : ObjectId("48445b4dc72153e9ad7f3bfb"),
"notificationID" : "78723asd5-vnbb-xv31-afe0-fa9asf164e4",
"notification" : "Notification #1",
"created" : ISODate("2016-11-21T20:33:53.695Z")
}
Any help is appreciated, thanks.

MongoDB has its own Javascript interpreter so, unless your MongoDB server has a different date than your system, it knows the current date so you easily use simple Javascript to compute the value you're looking for using a regular Date object and use it in your query.
var d = new Date();
d.setMonth(d.getMonth() - 1); //1 month ago
db.data.find({created:{$gte:d}}); //change "data" for your collection's name
If you need a different date than your database's, I'm afraid you'll have to somehow pass it as a parameter.

const now = new Date()
const temp = new Date(now).setMonth(now.getMonth() - 6);
const priorSix = new Date(temp)
Table.find({"date" : {$gte: priorSix, $lt: new Date()}}, (err, tables) => {
if(err) throw new Error(err)
res.status(200).json(tables)
}).populate('foodList.item')
This code worked for me. It retrieves documents of the last 6 month :)

Related

Meteor - Filter collection items published by dates

I am currently trying to filter a meteor collection based on two parameters they are: currentDate and coming from the collection dateEventEnds.
This is my current publish code:
Meteor.publish('recursos', function() {
let today = Date.now();
return Recursos.find({ 'recursos.fechaEnd': { $gt: today }});
});
Which is effectively not doing anything. I think this is due to:
Date.now() producing the date in milliseconds. Ex: 1463058648464
While recursos.fechaEnd has it stored like this: "2016-04-30T00:00:00.000Z"
Have also tried using: new Date(), but still nothing happens:
Meteor.publish('recursos', function() {
let today = new Date();
return Recursos.find({ 'recursos.fechaEnd': { $gt: today }});
});
new Date() results are like this: Thu May 12 2016 09:50:16 GMT-0400 (Eastern Daylight Time)
So it looks like the issue revolves around the way dates are presented. How could I change them to both use the same date format? Is it by changing them to Milliseconds?
The template where I need to do the filtering is suscribe to both the collection and an EasySearchIndex which looks like this:
RecursosIndex = new EasySearch.Index({
collection: Recursos,
fields: ['clase', 'direccion.city'],
engine: new EasySearch.MongoDB({
sort: () => ['fechaStart']
})
});
Should the filtering happen here?
Thanks
Your logic is perfectly fine, Mongo is quite capable of searching and sorting by date fields. The problem is that your dates in Mongo are stored as strings and not as actual dates. If you look at an object you should see fields like:
A real date:
"createdAt" : ISODate("2015-09-18T05:42:50.105Z")
A string:
"createdAt" : "2015-09-18T05:42:50.105Z"
To upgrade your existing dataset from strings to dates, run the following:
Recursos.find().forEach(function(r){
Recursos.update(r._id,{$set: { 'recursos.fechaEnd': new Date(r.fechaEnd) }});
});
Of course you can convert more than one date at a time, I suspect your object also has a fechaStart.

MongoDB : Time comparison

I have a field startTime in MongoDB collection that stores time in the following form:
2015-07-22 08:19:04.652Z
I would like to find all documents that has the startTime greater than or equal to yesterday's time(from exactly one day before). I tried using the $currentDate in the find query, but I was not able to make it work.
EDITED:
Sample Document:
{
"_id" : ObjectId("55af5241e4b0ec7c53360333"),
"startTime" : ISODate("2015-08-22T08:19:04.652Z"),
"sampleId" : "SS10"
}
EDITED 2: No aggregation framework allowed.
Compute the previous date first the pass it in find query.
In javascript:
var date = new Date();
date.setDate(date.getDate() - 1);
db.col.find({'startTime':{'$gte':date}})

Mongo Data not expiring

I'm trying to insert a record in mongo that expires in sometime.
getMessagesCollection().ensureIndex(new BasicDBObject("createdAt", 1), new BasicDBObject("expireAfterSeconds", 10));
I insert my data like this
Map map = new HashMap();
map.put("_id", mongoMessage.getObjectId());
// Other code
map.put("createdAt", new Date());
getMessagesCollection().insert(convertToDBObject(map))
the field createdAt is a date and before inserting the object looks like this
{ "_id" : "551bf9b72bea951ecf53fc5f" , "createdAt" : { "$date" : "2015-04-01T09:59:19.723Z"} , ...}
But the record is not getting deleted. Can someone tell me what I'm doing wrong?
Looks like you're incorrectly creating the date.
Check out how it's done here
Date now = new Date();
BasicDBObject time = new BasicDBObject("ts", now);

Query a Timestamp in MongoDB

MongoDB document sample is given below:
{
"_id" : ObjectId("5f2df113bdde22f1043g45gg"),
"cd" : 1395376406,
"dob" : 552026006,
"e" : "test#gmail.com",
"g" : "M"
}
I need query to get birthday list for today using dob(date of birth) field(timestamp).
Thanks in advance!
I am not sure how elegant my solution is, but it should work
var start = new Date();
start.setHours(0,0,0,0);
var end = new Date();
end.setHours(23,59,59,999);
db.collection.find({dob:{$gt:start.getTime(), $lt:end.getTime()}})
Since MongoDb doesn't have any inbuilt functions/operations to support parsing raw timestamps and extracting information from them, you need to do the operation by passing a custom java script function to the server and get it executed there. This function would be executed for each record though.
db.collection.find({$where:function(){
var recDate = new Date(this.dob);
var recDay = recDate.getDate();
var recMonth = recDate.getMonth();
var today = new Date();
var todayDate = today.getDate();
var todayMonth = today.getMonth();
return (recDay == todayDate && recMonth == todayMonth);
}});
The function simply checks if any record's day and month match today's day and month.
Although this works for timestamps, you should take advantage of MongoDBs ISODate data type whenever you store date information. This enables us to use various operators and functions on these fields. Moreover they would be faster. If your document had the below structure:
{
"_id" : "1",
"cd" : 1395376406,
"dob" : ISODate("2014-11-19T08:00:00Z"),
"e" : "test#gmail.com",
"g" : "M"
}
Where, the dob field is of ISODate type. You could easily do a aggregate operation to fetch the results.
var todayDate = ISODate().getDate();
var todayMonth = ISODate().getMonth();
db.collection.aggregate([
{$project:{"day":{$dayOfMonth:"$dob"},
"month":{$month:"$dob"},
"_id":1,"cd":1,"dob":1,"e":1,"g":1}},
{$match:{"day":todayDate,"month":todayMonth}},
{$project:{"cd":1,"dob":1,"e":1,"g":1,"_id":1}}
])
The above operation utilizes the functions and operations that are allowed on a ISODate field. Querying becomes a lot easier and better.

Unable to get some info in a subdocument

I am trying to get a value in my mongoDB collection. I would like to get the title of a movie and the sales (nbSold) of this movie for the current month.
Here is how my data are stored :
"_id" : ObjectId("52e6a1aacf0b3b522a8a157a"),
"title" : "Pulp Fiction",
"sales" : [
{
"date" : ISODate("2013-11-01T00:00:00Z"),
"nbSold" : 6
},
{
"date" : ISODate("2013-12-01T00:00:00Z"),
"nbSold" : 2
}
]
I'm using mongoose and this is how I build my query for the december of 2013 :
var query = Movie.find({"title":"Pulp Fiction"}, "title sales.nbSold")
.where("sales.date")
.equals(new Date("2013-12-01"));
However, this is the output that I am receiving :
{ title: 'Pulp Fiction', sales: [ { nbSold: 6 }, { nbSold: 2 } ] }
I would like to have only the title associated with the nbSold of the current month (2 in my case). What is the correct way to do this ?
Thanks a lot for your help.
First off, you should close your where call. You should call .exec(callback) when you're done comparing, and you should be using select instead of equals along with $elemMatch. Try this:
var query = Movie.find({"title":"Pulp Fiction"}, "title sales.nbSold")
.where("sales.date")
.select({ sales: { $elemMatch: new Date("2013-12-01") }})
.exec(function(err, doc) {
return console.dir(doc);
});
You should also have a callback. I ran this on my machine, and it definitely works. I posted code earlier that wasn't quite right, but this does the trick. See the documentation for an example.
Also, I'd be concerned as to how you're seeing if the date matches. If the time is off in your Date object but the date matches, Mongo won't find a match. And I don't know exactly how it works in Mongo, but in JavaScript, you can't compare two Date objects directly for equality as they are both different objects with the same value, so you may come across that problem as well. See this post for an example on how to do it.