MongoDB
 SQL >> Database >  >> NoSQL >> MongoDB

Trovare compleanni nei prossimi 30 giorni con MongoDB

L’approccio migliore è usare l’aggregation framework, perché evita JavaScript lato server e lavora direttamente nel motore MongoDB.

Con MongoDB 3.5.11 e versioni successive puoi usare $dateFromParts per costruire la data di compleanno di quest’anno e del prossimo, quindi calcolare quanti giorni mancano.

var today = new Date();
db.birthdays.aggregate([
  { $addFields: {
      today: today,
      birthdayThisYear: { $dateFromParts: { year: { $year: today }, month: { $month: "$birthday" }, day: { $dayOfMonth: "$birthday" } } },
      birthdayNextYear: { $dateFromParts: { year: { $add: [1, { $year: today }] }, month: { $month: "$birthday" }, day: { $dayOfMonth: "$birthday" } } }
  }},
  { $addFields: { nextBirthday: { $cond: [ { $gte: ["$birthdayThisYear", "$today"] }, "$birthdayThisYear", "$birthdayNextYear" ] } } },
  { $project: { name: 1, birthday: 1, daysTillNextBirthday: { $divide: [ { $subtract: ["$nextBirthday", "$today"] }, 86400000 ] }, _id: 0 } },
  { $match: { daysTillNextBirthday: { $lte: 30 } } },
  { $sort: { daysTillNextBirthday: 1 } }
])