Need help on Mongoid date range query - mongodb

I need a help on mongoid date range query.
I am trying to query events that spans over certain date range.
The event collection has two fields in the database start_date and end_date.
What would be the query to, for example, find events that occur between 04-18-2015 to 04-28-2015?

This might be helpful to you :
db.collectionName.find({
"start_date": { $lt: endDate }, // add end date here
"end_date": { $gt: startDate } // add start date here
});

Related

I can not get dates after my current date

I want to obtain the records that the "FECHA_FIN" field is greater than or equal to today's date.
this is an example of my data:
but with this query:
db.getCollection('susp_programadas').find( {"FECHA_FIN":{ $gte: new Date("YYYY-mm-dd") }} )
I do not get results, what am I doing wrong? Thank you
You can convert the date to an ISO date and query that way. Since you stored the date as a string mongo has no idea how to query it against an ISO date without conversion.
If you stored your date in mongo as the default ISO date then you could have easily done this:
db.getCollection('susp_programadas').find({"FECHA_FIN":{$gte: new Date()}})
So this is how you can do it now:
db.getCollection('susp_programadas').aggregate([
{
$project: {
date: { $dateFromString: { dateString: '$FECHA_FIN' }}
}
},
{ $match: { date: { $gte: new Date() }}}
])
You can use the $dateFromString in an aggregate query with a $match to get the results you want. Note that $dateFromString is only available in MongoDB version 3.6 and up.
If there is no way to convert your data to ISODate or upgrade your DB you could also consider another solution which via $where:
db.getCollection('susp_programadas').find({
$where: function(){
return new Date(this.FECHA_FIN) > Date.now()
}
})
However that solution suffers from the fact that $where can not use indexes so have that in mind.

in mongodb documnets date fields chagefrom month to date

I have a 6000 records with a problem: test_date is saved wrongly; for example for a date in the 2nd month the data is mistakenly saved as the 4th month:
"test_date" : ISODate("2017-04-02T00:00:00.000+0000"),
I need to change month to 02 and date to 04; I need a query to run on mongochef to change these fields.
Use $set to update fields in mongodb,
db.collection.update({
"test_date": ISODate("2017-04-02T00:00:00.000+0000")
}, {
$set: {
"test_date": ISODate("2017-02-04T00:00:00.000+0000")
}
}, {
multi: true
});
Note: this command will set same date "YYYY-MM-DDThh:mm:ssTZD" for all matches

How to get number of logins per day from a timestamp table in MongoDB?

I have a table in MongoDB which looks like this:
USERID | EVENT TYPE | TIMESTAMP
Every time a user logs in, a new entry is added to this table. I want to retrieve a number of events from a given day and that day, so I want to get something like
01/01/2016 - 5 events
and so on
How can I achieve this?
You can use aggregation.
Something like
db.collection.aggregate([
{
$match: {TIMESTAMP: timestamp}
},
{
$group: {
_id: "$TIMESTAMP",
events: {$sum: 1}
}
}
])
The match says that it has to match the timestamp.
The group says "Group by TIMESTAMP and add 1 to a new field called events"
Just change the lowercase timestamp to your desired timestamp.
or if you want only one timestamp
db.testCollection.find({TIMESTAMP: timestamp})
--
Or you could change your schema to something like
{
_id: userid,
events: [
{
type: "",
timestamp: timestamp
}
]
}
This would use mongodb's option to create arrays instead of just plain values.
Edit
You have to make querys where timestamp is in between. Else this wont work as expected. Gist

find document in today's date range in mongodb

I have a collection, Plans. I want to find everything within the range of one month. Here is a sample of what the data could look like:
{
"_id": "someid",
"dateStart": ISODate("2015-03-01T00:00:00Z"),
"dateEnd": ISODate("2015-03-31T00:00:00Z"),
"items": [
"someotherid"
]
}
How can I find the Plan such that today's date is between dateStart and dateEnd?
To find a Plan such that today's date is between the dateStart and dateEnd fields, create a date object that holds the current date then use the $lt and $gt query operators on the date fields to query documents where today's date falls between the two fields:
currentDate = new Date();
Plans.find({
dateStart: { $lt: currentDate },
dateEnd: { $gt: currentDate }
});
date1 = new Date('3/1/15');
date2 = new Date('4/1/15');
Plans.find({
startDate: {$gte: date1},
endDate: {$lt: date2}
});
New Date objects initialize to 00:00:000 so you can use that to your advantage here. Also note that "less than 4/1" is equivalent to "less than or equal to midnight on 3/31" - but the former is much easier to write.
Also note that moment is a super handy utility for doing manipulations like this. For example: moment().endOf('month').toDate()
To add the package just do:
$ meteor add momentjs:moment

Meteorjs Mongodb how to query a date with momentjs

In Meteor, I create a winner document this way:
var winner = {
participant_id: array[randomIndex]["_id"], //don't worry about the array[randomIndex]
creation_date: new Date()
};
id = Winners.insert(winner);
Later, I want to know how many winners I have today. I tried it many ways, but I couldn't succeed to get the right result.
The last thing I tried is this one:
Winners.find({creation_date: {"$gte": moment().startOf('day'), "$lt": moment().add('days',1)}}).count();
But the result is always equal to zero.
I guess the reason is that moment().startOf('day') is not a date object but I've no clue how to query it the right way.
You need to convert the moment object back to a Date so meteor/mongo can process the query. You can do that by appending a call to toDate like so:
var startDate = moment().startOf('day').toDate();
var endDate = moment().add('days',1).toDate();
Winners.find({creation_date: {$gte: startDate, $lt: endDate}}).count();
Try this:
// the number of milliseconds since 1970/01/01:
creation_date:new Date().getTime()
and
// you can still use moment:
moment().startOf('day').valueOf()
// query:
Winners.find({
creation_date: {
"$gte": moment().startOf('day').valueOf(),
"$lt": moment().add('days',1).valueOf()
}
}).count();