How to remove only one or two fields from documents in mongodb?
You need to explicitly include fields when using aggregation either via various pipeline operations or via $project
. There currently isn't a way to return all fields unless explicitly defined by field name:
$project : {
_id : 0,
"Name" : 1,
"Address" : 1
}
You can exclude the _id
using the technique you used and as shown above.
From v4.2, you can make use of $unset
aggregate operator to remove single or multiple fields. You can also exclude a field or fields from an embedded document using the dot notation.
To remove a single field:
db.coll.aggregate([ { $unset: "_id" } ])
To remove multiple fields:
db.coll.aggregate([ { $unset: [ "_id", "name" ] } ])
To remove embedded fields:
db.coll.aggregate([
{ $unset: [ "_id", "author.name" ] }
])