vibhor1997a
vibhor1997a

Reputation: 2376

convert string to date in mongodb?

I am using find to get the result then I'm applying Array.prototype.filter in javascript to filter the dates in between 2 given date strings in format dd-mm-yyyy.

let query = {};
req.query.query && (query.name = new RegExp(req.query.query, 'i'));
req.query.gender && (query.gender = new RegExp(`^${req.query.gender}$`, 'i'));
Student.find(query, { roll: 1, name: 1, _id: 0, email: 1, DOB: 1, gender: 1 }, (err, students) => {
    if (err) {
        next(err);
    }
    else {
        if (req.query.DOB_from && req.query.DOB_to) {
            let from = toDate(req.query.DOB_from);
            let to = toDate(req.query.DOB_to)
            res.send(filterBetweenDates(students, from, to));
        }
        else {
            res.send(students)
        }
    }
});


/**
 * Returns time val in mil secs from a date string in Indian format i.e dd-mm-yyyy
 * @param {string} dateStr 
 */
function toDate(dateStr) {
    let a = dateStr.split('-').map(Number);
    let d = new Date(a[2], a[1] - 1, a[0]);
    return d.getTime();
}

/**
 * Filters the result which matches the date
 * @param {Student1[]} students resultant students array
 * @param {Number} from time val in millisecs(from)
 * @param {Number} to time val in millisecs(from)
 */
function filterBetweenDates(students, from, to) {
    return students.filter(({ DOB }) => {
        return (from <= toDate(DOB)) && (to >= toDate(DOB));
    });
}

The issue I'm facing is that the dates are in dd-mm-yyyy format saved as a string And also the input is in the same format as string. So, I'm first applying other queries and then filtering according to the dates. Is there a way I can do this in the query itself?

Edit:

Sample Collection

    [
    {
        "name": "vib",
        "roll": 413,
        "email": "[email protected]",
        "DOB": "25-07-1997",
        "gender": "Male"
    }
    {
        "name":"abc",
        "roll":123,
        "email": "[email protected]",
        "DOB": "07-11-2000",
        "gender": "Female"
    }
]

Upvotes: 2

Views: 4019

Answers (1)

Ashh
Ashh

Reputation: 46451

You can use $dateFromString aggregation which change your string DOB to date and then you can $match the date and for changing user date format you can use moment libaray

db.collection.aggregate([
  {
    "$addFields": {
      "date": {
        "$dateFromString": {
          "dateString": "$DOB"
        }
      }
    }
  },
  { "$match": { "date": { "$lte": date, "$gte": date }}}
])

Upvotes: 4

Related Questions