I have a query like this (simplified):
db.report.aggregate([{
$match: {
main_id: ObjectId(\"58f0f67f50c6af16709fd2c7\")
}
},
From mongo v3.4 you could use $addFields in conjunction with $project
to avoid to write all the fields in $project
that could be very tedious.
This happen in $project
because if you include specifically a field, the other fields will be automatically excluded.
Example:
{
$addFields: { my_new_id_name: "$_id" }
},
{
$project: { _id: 0 }
}
if you are using find
method you can't do this, but if you using aggregation
it is very easy like this:
db.collectionName.aggregate([
{
$project: {
newName: "$existingKeyName"
}
}
]);
You can achieve this by adding a $project stage at the end of your pipeline like this :
{ $project: {
_id: 0,
name: "$_id",
count: 1,
sum: 1
}
}
try it online: mongoplayground.net/p/QpVyh-0I-bP
db.report.aggregate(
{
$group: {_id: '$name'}
},
{
$project:{
name:"$_id",
_id:false} }
)