-1

I'm currently try to do a search with PyMongo/Mongo that'll allow to me bring up results of entries within a specific date range. I have a database of apartments that are unavailable on specific dates. Here's an example of what a mongo document looks like at the moment (dates are in format 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"
    }
]

Essentially, I need to search for results that don't fall under the range of dates in unavailable. How would I go about this? Any help is appreciated!

Note: I can change the format of the dates if required if it'll make searching easier.

4

1 回答 1

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

请注意,这不包括任何没有“不可用”记录的文档。但是做一个查询来得到这些是微不足道的。

于 2013-10-18T00:10:01.473 回答