KingFish
KingFish

Reputation: 9153

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 }}])

Upvotes: 10

Views: 18313

Answers (3)

DarkCrazy
DarkCrazy

Reputation: 576

You can do this just with the exact syntax that you wrote in your question.

Example document: Person

{
  _id: ObjectId('6023a13b756e30fec9f77b26'),
  name: 'Pablo',
  lastname: 'Presidente',
}

If you do and aggregation, with $lookup you can remove, let's say the _id field like this:

db.person.aggregate( [ { task1 }, { ... }, { taskN }, { $project: { _id: 0 }}])

Also this way you can exclude fields for other related documents to your aggregation; you would do that like this:

db.person.aggregate( [ { task1 }, { ... }, { taskN }, { $project: { _id: 0, 'otherDocument._id': 0 }}])

Performance wise I don't know if this is any good, but leaving that aside, this works like a charm!

More info: https://docs.mongodb.com/manual/reference/operator/aggregation/project/#exclude-fields-from-output-documents

Also, you can use $unset but this I haven't tried out.

From the docs:

$unset and $project

The $unset is an alias for the $project stage that removes/excludes fields

If you are doing a simple find, is mostly the same, here are the docs with some examples: https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/#return-all-but-the-excluded-fields

Hope this is useful, best regards!

PR

Upvotes: 1

Prashant Pokhriyal
Prashant Pokhriyal

Reputation: 3827

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" ] }
])

Upvotes: 11

WiredPrairie
WiredPrairie

Reputation: 59763

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.

Upvotes: 8

Related Questions