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

261
Views
Mongodb, verifique si mi rango de consulta no se superpone a una lista de rangos de fechas en mongodb

tengo los siguientes datos:

 const Availabilities = new Schema({ id: Number, reservations: [{ from: Date, to: Date }] }); const Availability = mongoose.model('Availability', Availabilities);

Básicamente, quiero obtener una lista de productos en los que las fechas no se superpongan con la consulta.

 [ { id: 1, reservations: [ { from: '2022-01-01', to: '2022-03-31', }, { from: '2022-04-01', to: '2022-06-01', }, ], }, { id: 2, reservations: [ { from: '2022-01-01', to: '2022-12-31', }, ], }, { id: 3, reservations: [ { from: '2022-02-01', to: '2022-06-30', }, ], }, ]

y quiero filtrar todos los que no están en un rango específico. Ejemplo:

 query = { from: "2022-07-01", to: "2022-08-31" }

debería volver

 [ { id: 1, reservations: [ { from: '2022-01-01', to: '2022-03-31', }, { from: '2022-04-01', to: '2022-06-01', }, ], }, { id: 3, reservations: [ { from: '2022-02-01', to: '2022-06-30', }, ], }, ]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Simplemente puede verificar si se cumple una de las dos condiciones, ya sea:

  1. to es más pequeño que el inicio de su entrada (lo que significa que la sesión terminó antes)
  2. from es más grande que el final de su entrada (es decir, la sesión comenzó después)

Así es como se verá en el código:

 db.collection.aggregate([ { $match: { reservations: { $elemMatch: { $or: [ { to: { $lt: "2022-07-01" }, }, { from: { $gt: "2022-08-31" } } ] } } } }, { $addFields: { reservations: { $filter: { input: "$reservations", cond: { $or: [ { $lt: [ "$$this.to", "2022-07-01" ] }, { $gt: [ "$$this.to", "2022-08-31" ] } ] } } } } } ])

Parque infantil Mongo

about 4 years ago · Juan Pablo Isaza 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!