Raphael
Raphael

Reputation: 119

Is there a way to 'remove' a field during a mongo aggregation?

Is there a way to remove a field during an aggregation? I have a result that looks like this:

{
"firstName":"Patient1",
"lastName":"last",
"addresses":[
    {
     "street1":"1011 Happy Lane",
     "street2":"Apt 1",
    },
],
"phone":"11111111"
}

I am trying to exclude 'addresses' from the result:

{
"firstName":"Patient1",
"lastName":"last",
"phone":"11111111"
}

I found $unset but only seems to work on update.

Also I don't want to manually 'group' the other items because I need to return everything but the attributes I want to exclude. Selectively adding seems very easy in aggregation but selectively removing seems a bit more involved. Appreciate any ideas here.

Upvotes: 2

Views: 2474

Answers (1)

B. Fleming
B. Fleming

Reputation: 7220

Use a $project stage in your pipeline. You have two options available to you when using a projection.

The first is you can whitelist the returned fields by specifying the fields you want to include with a value of 1. The projection stage would look something like this:

{ $project: {
    firstName: 1,
    lastName: 1,
    phone: 1
}}

The second is you can blacklist the returned fields by specifying the fields you don't want to include with a value of 0. The projection stage would look something like this:

{ $project: {
    addresses: 0
}}

Both approaches have their merits and which one you should use depends largely on your use case. A good rule of thumb is that if you will only ever want certain fields and don't want to modify your projection stage when new fields are added, you should use a whitelist approach, but if you only want to exclude certain fields while allowing any new fields to be included in the results, you should use a blacklist approach.

Upvotes: 2

Related Questions