Finding dates and ignoring time and date in mongoDB node.js
I am using node.js and monodb database where I want to query records by date and I want to ignore time and date, only month and year will be matched here, this is my code: -
collection.find({ date: { "$gte": sDate, "$lt": eDate) } }).count(function (e, c) {
});
does this work but matches date and time and also how can i only match months and years? Please help me to solve this problem.
Edit: - some data from the collection: -
{
"_id" : ObjectId("5535e76f82a964d011e34fcf"),
"VisitorId" : "5535e72a82a964d011e34fcb",
"date" : ISODate("2015-01-21T06:00:15.761Z"),
}
{
"_id" : ObjectId("5535e75f82a964d011e34fcf"),
"VisitorId" : "5535e72a82a964d011e34fcb",
"date" : ISODate("2015-04-21T06:00:15.761Z"),
}
I will pass two parameters ie {month: "1", year: "2015"};
and the output should display the first documents.
thank
source to share
You can use the operator in a query : $where
collection.find({
"$where": function() {
return this.date.getMonth() == 0 && this.date.getFullYear() == 2015
}
}).count(function (err, data) {
// Handle err
});
However, query performance is quite compromised as it requires a table scan to use , a global lock is required. You should only use if you cannot express your request with a different operator. If you must use , try including at least one other standard query operator to filter the result set. $where
$where
$where
Other options are to change your schema and store the month in its own property (if it's a common field in your queries). You guarantee the best query performance since the field can be indexed.
Another option would be to query for a specific month and year, creating a query object that only looks for the start and end of that specific month.
var sDate = new Date(2015, 0, 1);
var eDate = new Date(2015, 1, 1);
collection.find({ date: { "$gte": sDate, "$lt": eDate) } }).count(function (e, c) {
});
source to share