1

I'm trying to get groups for a user only if the user is part of that group and its membership is true. Here is the group schema

{
        "isDefault": false,
        "users": [
            {
                "membership": true,
                "userId": "asd1234"
            },
            {
                "membership": false,
                "userId": "asdio21038028355"
            },
            {
                "membership": false,
                "userId": "as2398asjdhj"
            }
        ],
        "uuid": "c4vxitr33a9hb19n05iuqxlv1ycp47",
}

This is what I'm trying to get Groups for the user

Group.find({ 'users.membership': true, 'users.userId': 'asdio21038028355' })

Expected results should be an empty array but it is returning the above group as well.

1 Answer 1

6

To match an array item by multiple fields use $elemMatch, otherwise only one match needs to be fulfilled to return the doc.

https://docs.mongodb.com/manual/reference/operator/query/elemMatch/#op._S_elemMatch

https://mongoplayground.net/p/UB-Z0GX-CYq

Group.find({
  users: {
    $elemMatch: {
      "membership": true,
      "userId": "asdio21038028355"
    }
  }
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.