mongoDB 搜索查询 "dd/mm/yyyy" 字符串日期
mongoDB search query for "dd/mm/yyyy" string date
我在 MongoDB 中持有 'dd/mm/yyyy' 这样的日期。我想写一个查询 returns 两个日期之间的数据。
我找到了查询,但它们是针对 ISO 日期或 Unix 时间戳的。
我在下面写了一个查询,但它运行不正常
db.getCollection('col_cost').aggregate([
{
......
"$match":{
"$and": [
{"$or":[ { "costs.costDate": {
$lte: '01/04/2021',
$gte: '01/01/2021'
}},
{ "employeeID": 1)}
]
......
示例数据:
您可以查询嵌套文档中写成字符串的日期。首先将字符串转换为 iso。然后过滤iso日期信息。
db.getCollection('col_cost').aggregate([
{ "$addFields": {
"costs": {
"$map": {
"input": "$costs",
"in": {
"$mergeObjects": [
"$$this",
{
"costDate": {
"$cond": [
{ "$eq": ["$$this.costDate", ""] },
null,
{ "$dateFromString": { "dateString": "$$this.costDate", "format": "%d/%m/%Y" } }
]
}
}
]
}
}
}
}},
{
"$unwind" : "$costs"
},
{
"$match":{
"employeeID": ObjectId("5d89ca44cf4df62bddd64cf2"),
"$and": [
{"$or":[
{
"costs.status":"completed"
}
]},
{ "costs.costDate": {
$gte: ISODate("2019-12-01T21:00:00Z"), //start,
$lte: ISODate("2022-12-21T21:00:00Z") //end
}},
]
}
}
])
我在 MongoDB 中持有 'dd/mm/yyyy' 这样的日期。我想写一个查询 returns 两个日期之间的数据。
我找到了查询,但它们是针对 ISO 日期或 Unix 时间戳的。
我在下面写了一个查询,但它运行不正常
db.getCollection('col_cost').aggregate([
{
......
"$match":{
"$and": [
{"$or":[ { "costs.costDate": {
$lte: '01/04/2021',
$gte: '01/01/2021'
}},
{ "employeeID": 1)}
]
......
示例数据:
您可以查询嵌套文档中写成字符串的日期。首先将字符串转换为 iso。然后过滤iso日期信息。
db.getCollection('col_cost').aggregate([
{ "$addFields": {
"costs": {
"$map": {
"input": "$costs",
"in": {
"$mergeObjects": [
"$$this",
{
"costDate": {
"$cond": [
{ "$eq": ["$$this.costDate", ""] },
null,
{ "$dateFromString": { "dateString": "$$this.costDate", "format": "%d/%m/%Y" } }
]
}
}
]
}
}
}
}},
{
"$unwind" : "$costs"
},
{
"$match":{
"employeeID": ObjectId("5d89ca44cf4df62bddd64cf2"),
"$and": [
{"$or":[
{
"costs.status":"completed"
}
]},
{ "costs.costDate": {
$gte: ISODate("2019-12-01T21:00:00Z"), //start,
$lte: ISODate("2022-12-21T21:00:00Z") //end
}},
]
}
}
])