MongoDB $project embedded document to root level

Here is the solution which uses JavaScript variable.

# Set Object for what to project
var projectWhat = {'_id' : 0};

# Fill Object with keys
Object.keys(db.coll.findOne().name).forEach(function(x){
    projectWhat[x] = "$name." + x;
});

# Do Aggregate
db.coll.aggregate([{$project : projectWhat}])

And the output will be

{ "firstName" : "John", "lastname" : "Peters" }
{ "firstName" : "Mary", "lastname" : "Jones" }

Hope this helps.


MongoDB 3.4 has the new stage in aggregation pipeline - $replaceRoot, which does exactly what was asked.

https://docs.mongodb.com/manual/reference/operator/aggregation/replaceRoot/