Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove only one or two fields from documents in mongodb?

This is a very easy question, just having a really bad brain freeze. In my aggregation, I just want to remove the '_id' field by using $project but return everything else. However, I'm getting

$projection requires at least one output field

I would think it's like :

db.coll.aggregate( [ { $match .... }, { $project: { _id: 0 }}])
like image 376
Paul Avatar asked Feb 25 '14 23:02

Paul


2 Answers

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" ] }
])
like image 62
Prashant Pokhriyal Avatar answered Oct 22 '22 04:10

Prashant Pokhriyal


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.

like image 37
WiredPrairie Avatar answered Oct 22 '22 04:10

WiredPrairie