[ { $match: { "identifier.timeSeriesMetaId": ObjectId( "649155e254fed3423f67efec" ), isDeleted: null, }, }, { $facet: { rawResult: [ { $match: { date: { $gte: ISODate( "2022-10-31T23:00:00.000Z" ), $lt: ISODate( "2022-11-30T23:00:00.000Z" ), }, }, }, ], predecessor: [ { $match: { date: { $lt: ISODate( "2022-10-31T23:00:00.000Z" ), }, }, }, { $sort: { date: -1, }, }, { $limit: 1, }, ], follower: [ { $match: { date: { $gt: ISODate( "2022-11-30T23:00:00.000Z" ), }, }, }, { $sort: { date: 1, }, }, { $limit: 1, }, ], }, }, { $project: { items: { $concatArrays: [ "$predecessor", "$rawResult", "$follower", ], }, }, }, { $unwind: { path: "$items", }, }, { $replaceRoot: { newRoot: "$items", }, }, { $group: { _id: "$_id", date: { $first: "$date", }, value: { $first: "$value", }, identifier: { $first: "$identifier", }, }, }, { $densify: { field: "date", range: { step: 1, unit: "month", bounds: [ ISODate("2022-10-31T23:00:00.000Z"), ISODate("2022-11-30T23:00:00.000Z"), ], }, }, }, { $fill: { sortBy: { date: 1, }, output: { value: { method: "locf", }, }, }, }, { $densify: { field: "date", range: { step: 1, unit: "month", bounds: [ ISODate("2022-10-31T23:00:00.000Z"), ISODate("2022-11-30T23:00:00.000Z"), ], }, }, }, // this one adds 2022-10-30.... { $fill: { sortBy: { date: 1, }, output: { value: { method: "locf", }, "identifier.timeSeriesMetaId": { method: "locf", }, }, }, }, { $match: { date: { $gte: ISODate("2022-10-31T23:00:00.000Z"), $lt: ISODate("2022-11-30T23:00:00.000Z"), }, }, }, { $set: { "identifier.timeSeriesMetaId": ObjectId( "649155e254fed3423f67efec" ), }, }, ]