Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

604
Views
Consulta Mongodb. ¿Cómo encontrar la fecha más cercana a la actual?

Tengo una colección como esta:

 { "_id" : ObjectId("963fae9d93f4d930c98e269d"), "myDate":ISODate("2017-02-05T05:00:00.000Z"), "otherData":"blablabla" }, { "_id" : ObjectId("963fae9d93f4d930c98e269d"), "myDate":ISODate("2017-02-05T14:00:00.000Z"), "otherData":"blablabla" }, { "_id" : ObjectId("963fae9d93f4d930c98e269d"), "myDate":ISODate("2017-03-05T02:00:00.000Z"), "otherData":"blablabla" }, { "_id" : ObjectId("963fae9d93f4d930c98e269d"), "myDate":ISODate("2017-03-05T19:00:00.000Z"), "otherData":"blablabla" }

Dada la fecha actual (con minutos y segundos), quiero encontrar el registro más cercano a la fecha actual (por el campo "myDate").

Gracias

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Puede restar las fechas de su colección con la fecha actual, tomar el valor absoluto de la diferencia para considerar la fecha futura y luego usar ordenar y limitar para obtener el documento más cercano:

 db.a.aggregate([ { $project : { myDate : 1, otherData : 1, difference : { $abs : { $subtract : [new Date(), "$myDate"] } } } }, { $sort : {difference : 1} }, { $limit : 1 } ])

Puede usar un $project adicional si desea el campo de difference en el documento de salida. Además, en lugar de la fecha actual, puede usar cualquier otra fecha y encontrar la fecha más cercana a esa fecha.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!