$locf
Propagates the last observed non-null value forward within a partition, useful for filling missing data points in time-series datasets.
Syntax
{ $locf: { input: <expression>, sortBy: <document> } }
Parameters
input
objectrequiredExpression that resolves to the field whose value to propagate
sortBy
objectrequiredDocument specifying the sort order for the partition
Examples
Fill missing time series data
Propagate last non-null value for missing data within company partition
Query:
db.stores.aggregate([{ $match: { "company": { $in: ["First Up Consultants"] } } }, { $setWindowFields: { "partitionBy": "$name", "sortBy": { "sales.revenue": 1 }, "output": { "lastUpdatedDate": { "$locf": { "lastUpdated": 1 } } } } }])
Output:
Stores with missing lastUpdated values filled with last observed non-null value
Forward fill sensor readings
Use last observed value to fill gaps in sensor data
Query:
db.sensors.aggregate([{ $setWindowFields: { "partitionBy": "$sensorId", "sortBy": { "timestamp": 1 }, "output": { "filledReading": { "$locf": { input: "$reading", sortBy: { "timestamp": 1 } } } } } }])
Output:
Sensor data with missing readings filled using last observed values