Search code examples
arraysmongodbmongoosemongodb-query

Mongo How to get only available documents by date


I have documents that associated to students:

[
{
'_id': 1,
'name': 'Anna',
'vacation_start: '2024-01-01',
'vacation_end': '2024-01-03'
},
{
'_id': 2,
'name': 'Bob',
'vacation_start: '2024-01-01',
'vacation_end': '2024-01-05'
},
{
'_id': 3,
'name': 'Zenna',
'vacation_start: '2024-02-02',
'vacation_end': '2024-02-10'
}
]

How can i get students that only available from my input to my input?

For example my input: available_from=2024-01-04 available_to=2024-02-02 And i want to get only Anna in this filters.

I was thinking about $gt and $lt but i do not think that this is the right way


Solution

  • You can use $gte and $lt operators to filter a record between specific criteria

    Example -

    db.CollectionName.find({"whenCreated": {
        '$gte': ISODate("2018-03-06T13:10:40.294Z"),
        '$lt': ISODate("2018-05-06T13:10:40.294Z")
    }});
    

    Reference - https://www.mongodb.com/community/forums/t/how-can-i-match-all-data-between-two-date/189642