bobsov534 bobsov534 - 14 days ago 6
Javascript Question

Applying $cond inside subset in Mongodb/Mongoose Aggregation

Lets say I have this document:

{ "_id" : 1, "first_name" : "Matt", "roles": ['editor', 'publisher', 'siteAdmin'] }
{ "_id" : 1, "first_name" : "Harry", "roles": ['publisher', 'siteAdmin'] }
{ "_id" : 1, "first_name" : "Rob", "roles": ['editor'] }


Now I would like to use mongoose aggregation (
$cond
) to output this document.

How do I get this? I would appreciate your help in this.

{ "first_name" : "Matt", "isSiteAdmin": true }
{ "first_name" : "Harry", "isSiteAdmin": true }
{ "first_name" : "Rob", "isSiteAdmin": false }

Answer

A pipeline like the following should work for you

YourModel.aggregate([
    {
        $project: {
            _id: 0,
            first_name: 1,
            isSiteAdmin: {
                $setIsSubset: [["siteAdmin"], "$roles"]
            }
        }
    }
 ])