请试试这个:
db.yourCollectionName.aggregate([{
$addFields: {
/** converting month from string to num :: Dec to 12 & extracting date & year from string */
month: {
$indexOfArray: [[, "Jan", "Feb", "Mar", "Aprl", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]
, { $arrayElemAt: [{ $split: ['$db_date', " "] }, 1] }]
}
, date: { $toInt: { $arrayElemAt: [{ $split: ['$db_date', " "] }, 0] } }, year: { $toInt: { $arrayElemAt: [{ $split: ['$db_date', " "] }, 2] } }
}
}, {
/** db_date is being converted to format ISODate() from parts year + month + day & then to this : "2019-12-18" */
$addFields: {
db_date: {
$dateToString: {
format: "%Y-%m-%d", date: {
$dateFromParts: {
'year': '$year', 'month': '$month', 'day': '$date'
}
}
}
}
}
}, { $project: { 'month': 0, 'year': 0, 'date': 0 } },
{
/** Here we're converting ISODate() from input to like this : "2019-12-19", This is what you actually asked for */
$match: {
$expr: {
$eq: ['$db_date', {
$dateToString: {
format: "%Y-%m-%d", date: new Date()
}
}]
}
}
}
])
此查询应该可以帮助您获得所需的结果,但在我看来,进行这种转换是一项艰巨的任务,您通常可以通过在数据库设计时考虑您的事务然后将数据存储在DB 根据您的阅读要求,如果不是 - 以另一种方式,可以通过将代码中的输入转换为与存储在 DB 中的数据匹配来简化您的 DB!