1

I'm using mongoose 4.7.x and mongodb 3.2. I want to search all date without time. E.g update all obj with this date 2016-12-14.

In my database I have multiple datetime like this :

2016-12-14 00:00:00.000Z
2016-12-14 00:00:00.000Z

2016-12-14 01:00:00.000Z
2016-12-14 01:00:00.000Z

2016-12-14 02:00:00.000Z
2016-12-14 02:00:00.000Z

I tried this :

var query = {date: new Date('2016-12-14')};
var doc = {name: 'TEST'};
var options = {multi: true};

Model.update(query, doc, options, function(err, result){
    console.log('All data updated')
});

But this will just update all fields with time 00:00:00 because new Date() will returns the datetime.

How can I do to search all fields with a certain date without time ? I can change the model if it's necessary.

John
  • 4,711
  • 9
  • 51
  • 101

1 Answers1

5

You can do it in between a range of dates. Use $gte for the lower range, and $lt for the higher one (which is the next day) to keep it from selecting the next day at 00:00:00 hours.

var query = {
    date: {
        $gte: new Date('2016-12-14'),
        $lt: new Date('2016-12-15')
    }
};
var doc = {name: 'TEST'};
var options = {multi: true};

Model.update(query, doc, options, function(err, result){
    console.log('All data updated')
});

All documents between 2016-12-14 00:00:00.000Z and 2016-12-14 23:59:59.999Z will be updated.

Ron Dadon
  • 2,666
  • 1
  • 13
  • 27
  • Ohh I did't know `$gte` and `$lt`. It's so cool. Thank you soooo much @Ron ! – John Dec 14 '16 at 14:51
  • Do you know how can I find a double field in my database ? I tried this but It will returns me nothing : `db.getCollection('Model').find({longitude: 354.049987792969})` – John Dec 15 '16 at 11:03
  • According to this http://stackoverflow.com/a/35482037/4908482 mongoose does not support double out of the box and converts it to string, so maybe try to filter like this: `db.getCollection('Model').find({longitude: '354.049987792969'})` – Ron Dadon Dec 15 '16 at 11:44