在mongodb中将字符串转换为日期?

时间:2018-07-06 12:23:25

标签: javascript node.js mongodb mongoose

我正在使用find来获取结果,然后在JavaScript中应用Array.prototype.filter来过滤格式为dd-mm-yyyy的2个给定日期字符串之间的日期。

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));
    });
}

我面临的问题是日期以dd-mm-yyyy格式保存为string,并且输入的格式与字符串相同。因此,我首先要应用其他查询,然后根据日期进行过滤。我可以在查询本身中做到这一点吗?

编辑:

样品收集

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

1 个答案:

答案 0 :(得分:1)

您可以使用$dateFromString聚合将字符串DOB更改为日期,然后可以$match更改日期,并使用moment libaray < / p>

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