$facet with $project

Hello,
I am doing pagination with $facet, here i am also using $project to filter out which field I want to show but it is not working, If I made one with 0 then this error is showing

" Invalid $project :: caused by :: Cannot do exclusion on field status in inclusion projection "

Here is my code.

  db.roles.aggregate([
    {
        $facet : {
            'data' : [
                {$match : {'status' : { $ne : '2'}}},
                {$project : { '_id': 1, 'createdAt': 1, 'name' : 1, 'code' : 1, 'status' : 0 }},
            ],
            'pagination': [
                { "$count": "total" }
            ]
        }
    },
    { 
        $project: { 
            total: { $arrayElemAt: [ '$pagination.total', 0 ] },
            data: 1
        }
    }
]).pretty();

How to do projection with facet ? please help me.

Hi @atanu_samanta ,

The only field that is allowed to be 0 in a projection with other “1 projected” is _id.

If you.just don’t specify the status field in “data” project stage it will act as exclusion :slight_smile: , so remove "status" : 0 and it should work

Thanks
Pavel

3 Likes