Q:

Return a field from the match stage in the final project stage

I have an aggregation query set up in a Node.js script using Mongoose as following:
TestResult.aggregate([
                { $match:
                    {
                        Probe: parseInt(fieldsToSearch.probe),
                        TimeStamp: {
                            "$gte" : fieldsToSearch.queryBeginTimeStamp ,
                            "$lt" : fieldsToSearch.queryEndTimeStamp
                        }
                    }
                },
                { $group:
                    {
                        _id: "$Probe",
                        min : {
                            $min: "$Value"
                        },
                        max : {
                            $max: "$Value"
                        },
                        avg : {
                            $avg: "$Value"
                        }
                    }
                },
                { $project:
                    {
                        probe:"$_id",
                        _id: 0,
                        min: 1,
                        max: 1,
                        avg: 1,
                        TimeStamp : 1//"$TimeStamp"

                    }

                }])

However, in the last $project stage, I want to also return the original TimeStamp field which I used to match the record against. However, results obtained have no TimeStamp field. How do I fetch a field from an earlier stage, to the last project stage?

A:

You should give more info about your collection, but looking at the pipeline, you might want to add an _id composed from 2 fields - probe and timestamp, in the group stage:
$group:
{
    _id: {
        Probe: "$Probe",
        TimeStamp: "$TimeStamp"
    },
    min : {
        $min: "$Value"
    },
    max : {
        $max: "$Value"
    },
    avg : {
        $avg: "$Value"
    }
}

Otherwise you cannot get the timestamp field further in the pipeline.

