Thursday, April 28, 2016

How can I check given date is between two dates in mongodb?

Leave a Comment
{   "_id": {     "$oid": "asdf976"   },   "Categories": [{     "mainmodels": [{       "submodels": [{           "price": "2000",           "submodelname": "lumia021",          }, {           "price": "2000",           "submodelname": "lumia341",          }        ],       "Status": "Active",       "modelname": "lumia",       "fromdate": "15/04/2016",       "todate": "29/04/2016"     }],     "brand": "nokia"   }],   "rank": "1",   "name": "first Mobile station" }  {   "_id": {     "$oid": "asdf976"   },   "Categories": [{     "mainmodels": [{       "submodels": [{           "price": "2000",           "submodelname": "lumia a02",          }, {           "price": "2000",           "submodelname": "lumia trend",          }        ],       "Status": "Active",       "modelname": "lumia",       "fromdate": "20/04/2016",       "todate": "21/04/2016"     }],     "brand": "nokia"   }],   "rank": "2",   "name": "Zahid station" } {   "_id": {     "$oid": "asdf976"   },   "Categories": [{     "mainmodels": [{       "submodels": [{           "price": "2000",           "submodelname": "trend 45",          }, {           "price": "2000",           "submodelname": "trendz",          }        ],       "Status": "Active",       "modelname": "trend",       "fromdate": "10/04/2016",       "todate": "21/04/2016"     }],     "brand": "samsung"   }],   "rank": "3",   "name": "mobi cell station"  } 

Above i have added my data's which is stored in mongodb database . how can i find data only where ever "Status": "Active", "modelname": "lumia", "date":"19/04/2016"

above is my condtion that date thing only i can't able to solve here given date is between fromdate and todate then only it should give the result

i need to check given date (19/04/2016) which is between fromdate and todate after that i need to check "Status": "Active", "modelname": "lumia",

my controller:

exports.search = function(req, res) {  var condition = { 'modelname': 'lumia', 'Status':'Active'   };         Phone.find(condition).sort('-created').populate('user', 'displayName').exec(function(err, phones) {                 if (err) {                         return res.status(400).send({                                 message: errorHandler.getErrorMessage(err)                         });                 } else {                         res.jsonp(phones);                  }         }); }; 

schema:

var mongoose = require('mongoose'),     Schema = mongoose.Schema;  var submodelSchema = {    submodelname: {type:String, required: false},    price: {type:String, required: false},    Remainingphones: {type:String, required: false},    Bookedphones: {type:String, required: false},    Numofphones: {type:String, required: false}  };  submodelSchema  = 'new Schema('+ submodeleSchema +',{_id:true})';  var typeSchema = {    vtype: {type:String, required: false},    mainservices: {    Status: {type:String, required: false},    modelname : {type:String, required: false},    fromdate: {type: Date,default: Date.now},    todate: {type: Date,default: Date.now}    },    submodels: [submodelSchema], default:[] }; typeSchema  = 'new Schema('+typeSchema +',{_id:true})';  var PhoneSchema = new Schema({         rank: {                 type: String,                 default: '',                 trim: true         },         name: {                 type: String,                 default: '',                 trim: true         },    Categories: [typeSchema], default:[]   });  mongoose.model('Phone', PhoneSchema); 

4 Answers

Answers 1

I didn't understand your question properly but you should store your date as Date. and you can design your schema something like this

    fromDate: Date,     untilDate: Date 

and to find if the date falls between the dates that are stored in fromDate and untilDate you can use $gte and $lt

 $gte: fromDate,  $lte : untilDate 

Answers 2

If you want to find your query date between fromdate and todate and also check modelname and Status then can follow this condition.

Aaccording to your given model structure you need to use dot (.) notation to check your date like: Categories.mainmodels.fromdate and need to use $lte (less than or equal) and $gte (greater than or equal) operator.

var queryDate = '19/04/2016';  // or like: var queryDate = req.query.date; or as you sent   var condition = {        'modelname': 'lumia',        'Status':'Active',        'Categories.mainmodels.fromdate': {$gte: queryDate },        'Categories.mainmodels.todate': {$lte: queryDate } };  Phone.find(condition).sort('-created').// rest of code 

Answers 3

Just modify your condition variable to

var yourDate='19-04-2016';     var condition = {      'modelname':'lumia',      'Status':'Active',      'fromDate':{ $gte: yourDate},      'untilDate':{$lte : yourDate}  }; 

You can go through this documentation about $gte and $lte

https://docs.mongodb.org/manual/reference/operator/query/gte/

Also if the date is not in the proper format or if type of date is string you will have to explicitly parse it using Moment.js.

Below is the Link have a look at it: http://momentjs.com/docs/

Answers 4

Best way would be to save the date values as Date rather than String. While you are inserting the data, do => 'categories.mainmodels.fromdate':new Date('date-string') and same for the other date. This will create a Date type in db which will be easier to compare like below. Do follow the mm/dd/yyyy format to create new date;

var givenDate = new Date('04/19/2016'); (mm/dd/yyyy)

var condition = { 'modelname': 'lumia', 'Status':'Active', 'Categories.mainmodels.fromdate': {$gte: givenDate }, 'Categories.mainmodels.todate': {$lte: givenDate } };

Phone.find(condition).sort('-created').

Mind you, instead of just "date-string", while inserting/updating do new Date("date-string") which will create date and will allow you to compare like above.

If the value is date itself in db, remember to create the date from the string you want to compare with. In your case, where you have {$gte: 'date-string'} replace with {$gte: new Date('date-string')} and so for the other one. [This is to follow only if the data is already stored as date and it returns date value but not date string.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment