我目前正在尝试使用PyMongo / Mongo进行搜索,这将允许我调出特定日期范围内的条目结果。我有一个公寓数据库,在特定日期不可用。以下是mongo文档目前的样子(日期格式为 d-m-Y )。
"name":"apartmentName",
"unavailability": [
{
"@date_from": "21-01-2013",
"@date_to": "25-01-2013"
},
{
"@date_from": "08-12-2012",
"@date_to": "10-12-2012"
},
{
"@date_from": "06-12-2012",
"@date_to": "08-12-2012"
}
]
基本上,我需要搜索不属于不可用日期范围的结果。我该怎么做?任何帮助表示赞赏!
注意:如果要使搜索更容易,我可以根据需要更改日期的格式。
答案 0 :(得分:0)
假设您正在寻找YYYYDDMM形式的给定日期(例如下面示例中的“20121207”),您可以按如下方式使用聚合框架:
db.apts.aggregate([
// Produce one document for every unavailability record.
{$unwind:"$unavailability"},
// Reshape the results to spin the date around into sortable order.
{$project:{ name:1,
from : { $concat: [
{$substr:["$unavailability.@date_from",6,4]},
{$substr:["$unavailability.@date_from",3,2]},
{$substr:["$unavailability.@date_from",0,2]}
]
},
to : { $concat: [
{$substr:["$unavailability.@date_to",6,4]},
{$substr:["$unavailability.@date_to",3,2]},
{$substr:["$unavailability.@date_to",0,2]}
]
}
// Here, you could pass through additional fields from the original document.
}
},
// For each name, produce a count for every time the target date falls within the range.
{
$group: {
_id: "$name",
count: { $sum: { $cond: [ { $and: [
{$gte:["20121207","$from"]},
{$lte:["20121207","$to" ]}
]
} , 1, 0
]
}
}
// Here, you could pass through additional fields from the original document.
}
},
// Select only those documents for which the target date fell withiin none of the ranges
{$match:{count: 0}}
])
请注意,这不包括任何没有“不可用”记录的文档。但是进行查询以获得这些是微不足道的。