How can I filter documents from a collection by a string type field named "fecha_proximo_mantenimiento" (next_date_maintenance)?
Hopefully I understood your question correctly.
The query below will filter documents that have fecha_proximo_mantenimiento
with value older than 30 days.
[ { "$addFields": { "fecha_proximo_mantenimiento_timestamp": { "$subtract": [ "$$NOW", { "$toDate": "$fecha_proximo_mantenimiento" } ] } } }, { "$match": { "fecha_proximo_mantenimiento_timestamp": { "$gte": 1000 * 60 * 60 * 24 * 30 } } }]
First stage $addFields
adds new field (I called same as original with appended _timestamp
and it subtracts field value (which is also converted to Date, since your schema defined that as String) from Date.
Second stage $match
checks that subtracted result (in miliseconds) is greater than 30 days (you can also replace with 2592000000
if it's easier for you).
const hasta = moment(new Date()).add(30, 'days').format('YYYY-MM-DD');const desde = moment(new Date()).format('YYYY-MM-DD');const contrato= 0;Dispositivos.find( contrato, fecha_proximo_mantenimiento: { $exists: true }}, { _id: 0, 'informacion_equipo.ususario_red': 1, fecha_proximo_mantenimiento: 1 }) .where('fecha_proximo_mantenimiento') .gte(desde) .lte(hasta) .exec(function (err, result) { if (err) { console.log(err) } else { for (var x in result) { console.log('numero de documento: ', x, result[x]) } } });
It works too with find