Lo que quiero lograr es encontrar un documento específico en ese mes actual según la fecha proporcionada. La fecha se almacena como una cadena, para poder comparar la fecha, primero necesito convertir la fecha. Sin embargo, tengo problemas para convertir la cadena de fecha en una matriz anidada de objetos.
Mis colecciones:
{ sections: [{ fields: [{ name: 'Date', value: '2020-11-30T15:59:59.999Z' // this is string }, { name: 'Title', value: 'My book' }, { name: 'Author', value: 'Henry' } ] ] } }Lo que he probado:
1)
const existingReport = await Report.find({ $expr: { $gte: [ { $dateFromString: { dateString: "$sections.field[0].value", }, }, moment(payload.forPeriod).startOf("month").toDate(), ], $lt: [ { $dateFromString: { dateString: "$sections.field[0].value", }, }, moment(payload.forPeriod).endOf("month").toDate(), ], }, }); const existingReport1 = await Report.aggregate([ { $addFields: { formattedData: { $cond: { if: { $eq: ["$sections.field.value", "Date"], }, then: { $dateFromString: { dateString: "$sections.field.value", }, }, else: "$sections.field.value", }, }, }, }, ]);Simplemente puede hacer $toDate con la ayuda de 2 $reduce para iterar la matriz de sections y fields .
db.collection.aggregate([ { "$match": { $expr: { $eq: [ true, { "$reduce": { "input": "$sections", "initialValue": false, "in": { "$reduce": { "input": "$$this.fields", "initialValue": false, "in": { $or: [ "$$value", { $and: [ { $gte: [ { "$toDate": "$$this.value" }, new Date("2020-11-01") ] }, { $lte: [ { "$toDate": "$$this.value" }, new Date("2020-11-30") ] } ] } ] } } } } } ] } } } ])Aquí está el parque infantil de Mongo para su referencia.