简体   繁体   中英

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 }

A pipeline like the following should work for you

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM