简体   繁体   中英

Searching Dates and Ignoring time and date in mongoDB node.js

I am using node.js and monodb database where I want to query records based on date and I want to ignore time and date only month and year will be matched here is my code:-

  collection.find({ date: { "$gte": sDate, "$lt": eDate) } }).count(function (e, c) {
 });

this is working but matching date and time as well how I can match only month and year? Please help me to solve this problem.

Edit:- some data from 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 params ie {month:"1",year:"2015"};

and in output first docs should be display.

Thanks

You could use the $where operator in your query:

collection.find({
    "$where": function() { 
        return this.date.getMonth() == 0 && this.date.getFullYear() == 2015
    } 
}).count(function (err, data) {
   // Handle err
});

However, query performance is rather compromised because using $where alone requires a table scan, it takes a global lock. You should use $where only when you can't express your query using another operator. If you must use $where , try to include at least one other standard query operator to filter the result set.

Other options are to modify your schema and store the month in its own property (if it's a common field in your queries). You are guaranteed better query performance since the field can be indexed.

The other option will be when query a specific month and year, create a query object that only looks for the start and the 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) {
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM