MongoDB 2.6 introduced a new $$ROOT aggregation variable which almost does what you want: it will include the full document being processed in the current pipeline stage, so you don't need to know or specify what fields to include.
Taking your example aggregation and adding a fields
projection with $$ROOT
:
db.pipeline.aggregate(
{ $project: {
field3: {
$gt: ['$field1', 10]
},
fields: "$$ROOT"
}}
)
The output will include both new calculated field(s) and all the original fields:
{
"_id" : ObjectId("53b56cc542974939144cee2a"),
"field3" : false,
"fields" : {
"_id" : ObjectId("53b56cc542974939144cee2a"),
"field1" : 1,
"field2" : 2,
"field3" : 3
}
}
MongoDB 3.3.11 introduces the addFields
aggregation stage that does what you want. See this entry in MongoDB issue tracker: SERVER-5781 - Implement $addFields aggregation stage for using expression language to add new fields to a document.