Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

414
Visualizações
Querying database for documents within a specified date range using FastAPI and MongoDB

I have a collection in my MongoDB with records that have an attribute "timestamp" which is stored as type datetime

I want to use FastAPI to query and return all records which are within a given range of dates that I am passing on as query parameters.

db = client["tasks"]

async def list_activities(
    lower_date: str = "", upper_date: str = ""
):
    start_date = datetime.strptime(lower_date, "%d-%m-%Y")
    end_date = datetime.strptime(upper_date, "%d-%m-%Y")
    activities = (
        await db["activities"]
        .find({"timestamp": {"$gte": start_date, "$lt": end_date}})
        .to_list(1000)
    )
    return activities

On running this with some parameters for lower and upper dates, I'm being returned an empty list

However I wrote another program to test this

MONGODB_URL = os.getenv("MONGODB_URL")
mc = pymongo.MongoClient(MONGODB_URL)
tgdb = mc["tasks"]
tgcol = tgdb["activities"]
recordno = 1

for x in tgcol.find(
    {"timestamp": {"$gte": "2022-01-31 00:00:00", "$lt": "2022-02-06 00:00:00"}}
):
    print("Record No: " + str(recordno))
    recordno += 1
    print(x)

This on the other hand returns all the records within the date range just fine.

Any clue as to what I'm doing wrong with the first piece of code?

over 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda