Ray Purchase
Ray Purchase

Reputation: 762

How to Exclude a Field When Using an Inclusion Projection in MongoDB/Mongoose?

I have a lookup query in which I use an inclusion projection to filter out posts where published = false. I also need exclude a field, but I can't workout how to do it given the inclusion projection.

This is my aggregation:

{
...
        '$lookup': {
            'from': 'photos', 
            'localField': '_id', 
            'foreignField': 'postId', 
            'as': 'photoData'
        }
    }, {
        '$project': {
            '_id': 1, 
            'field1': 1, 
            'field2': 1, 
            'field3': 1, 
            'photoData': {
                '_id': 0, // ** I am trying to exclude this field **
                '$filter': {
                    'input': '$photoData', 
                    'as': 'photo', 
                    'cond': {
                        '$ne': [
                            '$$photo.published', false
                        ]
                    }
                }
            }
        }

I'm trying to exclude the '_id' field in the photoData lookup. Doing it like this with the '_id: 0' in the photoData projection gives a "Cannot do exclusion on field _id in inclusion projection". I've tried a few other methods as well with no success. Is there a way to do this?

Upvotes: 3

Views: 3332

Answers (1)

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59642

You can remove fields with this stage:

{ $unset: "photoData._id" } 

Upvotes: 2

Related Questions