我正在使用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"
}
]
答案 0 :(得分:1)
您可以使用$dateFromString
聚合将字符串DOB
更改为日期,然后可以$match
更改日期,并使用moment
libaray < / p>
db.collection.aggregate([
{
"$addFields": {
"date": {
"$dateFromString": {
"dateString": "$DOB"
}
}
}
},
{ "$match": { "date": { "$lte": date, "$gte": date }}}
])