I am trying to get the group where the current user is in. In this case the user can only be member of one group.

I tried the following but the I would have to loop trough the CollaborationGroup

    User currentUser = [SELECT Id, Contact.AccountId FROM User WHERE Id =: UserInfo.getUserId() LIMIT 1];
            List<CollaborationGroup> chattergroups = [SELECT Id,Name, (SELECT id,MemberId FROM GroupMembers WHERE MemberId = :currentUser.id LIMIT 1) From CollaborationGroup]


1 Answer 1


Remember that your SELECT subquery against GroupMembers does not perform any filtering on the CollaborationGroup list that's returned - it only filters the member data you get back as part of the CollaborationGroup sObjects.

So when you do this:

chatterGroups = [SELECT Id, Name, 
                        (SELECT id, MemberId 
                         FROM GroupMembers 
                         WHERE MemberId = :currentUser.id LIMIT 1) 
                 From CollaborationGroup];

what you get back is every single CollaborationGroup in your org, along with any GroupMember records where the MemberId is the current user.

Instead, you can use a semi-join:

chatterGroups = [SELECT Id, Name 
                 FROM CollaborationGroup
                 WHERE Id IN (SELECT CollaborationGroupId 
                              FROM CollaborationGroupMember 
                              WHERE MemberId = :UserInfo.getUserId())];

That will in fact filter the returned group list to only those groups of which the current user is a member.

This pattern is widely applicable to situations where you need to filter a parent object based on the presence or absence of a child object matching some criteria or other.

  • Thanks for your explanation. In this case where do you refer to in the documentation to know that CollaborationGroupMember is a child of CollaborationGroup?
    – Thomas
    Commented Sep 4, 2018 at 21:11
  • I generally just look at the SOAP Reference for the object I want.
    – David Reed
    Commented Sep 4, 2018 at 22:31
  • Ah ok I expected something as the Datamodel Chatter Objects and maybe an easier way in the Org itself. But thanks for the info!
    – Thomas
    Commented Sep 5, 2018 at 6:37
  • Oh, sorry, I misunderstood. You want the Chatter ERD.
    – David Reed
    Commented Sep 5, 2018 at 11:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .