Pergunta

I have an array of objects containing dates of when a hotel is available to book within Mongo. It looks something like this, using ISO Date formats as said here.

Here's what document looks like, trying to keep it short for the example.

available: [
    {
        "start":"2014-04-07T00:00:00.000000",
        "end":"2014-04-08T00:00:00.000000"
    },
    {
        "start":"2014-04-12T00:00:00.000000",
        "end":"2014-04-15T00:00:00.000000"
    },  
    {
        "start":"2014-04-17T00:00:00.000000",
        "end":"2014-04-22T00:00:00.000000"
    },
]

Now, I need query two dates, check in date and check out date. If the dates are available, Mongo should return the document, otherwise it won't. Here are a few test cases:

2014-04-06 TO 2014-04-08 should NOT return.

2014-04-13 TO 2014-04-16 should NOT return.

2014-04-17 TO 2014-04-21 should return.

How would I go about forming this in to a Mongo query? Using $elemMatch looked like it would be a good start, but I don't know where to take it after that so all three examples I posted above work with the same query. Any help is appreciated.

Foi útil?

Solução 2

Well I actually hope your documents have real ISODates rather than what appears to be strings. When they do then the following query form matches as expected:

db.collection.find({ 
    "available": {
        "$elemMatch": { 
            "start": { "$gte": new Date("2014-04-17") },
            "end":   { "$gte": new Date("2014-04-21") } 
        }
    }
})

Outras dicas

db.collection.find({ 
    "available": {
        "$elemMatch": { 
            "start": { "$lte": new Date("2014-04-17") },
            "end":   { "$gte": new Date("2014-04-21") } 
        }
    }
})

How about this command?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top