Nirmal
Nirmal

Reputation: 161

Getting computed column in MongoDb

Hi I am using MongoDb and in that I need a computed column while retrieving a list of collection for groups. Group collection has members array which contains documents having _id, member_id, member_type. I need to check if current user is admin for that group or not. If member_type is 1 then it is admin and also user must be part of members array.

Collection Structure:

// collection: user_groups

    {
     "_id" : ObjectId("5a339d6cc2d708402ebe53e5"),
     "group_description" : "desc",
     "members" : [
       {
          "member_id" : ObjectId("5a335b81d51ba494223227bb"),
          "member_type" : 1,
          "created_at" : ISODate("2017-12-15T15:31:16.566+05:30"),
          "updated_at" : ISODate("2017-12-15T15:31:16.566+05:30"),
          "_id" : ObjectId("5a339d6cc2d708402ebe53e6")
       }
     ],
     "is_admin" : false
     }

I used following query but returns false, it should return true.

db.user_groups.aggregate([{$match:{_id:ObjectId("5a339aaac2d708402ebe53e5")}},
{$project:{members: 1,group_description:1,is_admin:{$cond:[{$and:[{$eq:
['$members.member_type',1]},{$eq:
['$members.member_id',ObjectId("5a335aaad51ba494223227bb")]}]},true,false]}}}])

Upvotes: 1

Views: 186

Answers (1)

Alex
Alex

Reputation: 21766

You need to $unwind your $members array for your code to work. Your code would have worked if members was an embedded sub-document rather than an array of embedded sub-documents.

db.user_groups.aggregate([{
        $match: {
            _id: ObjectId("5a339d6cc2d708402ebe53e5")
        }
    },
    {
       $unwind:"$members"
    },
    {
        $project: {
            members: 1,
            group_description: 1,
            is_admin: {
                $cond: [{
                    $and: [{
                        $eq: ['$members.member_type', 1]
                    }, {
                        $eq: ['$members.member_id', ObjectId("5a335b81d51ba494223227bb")]
                    }]
                }, true, false]
            }
        }
    }
])

Upvotes: 1

Related Questions