1

I need to query all document where groupData.users.userId = 'aFHJBrKu54y5mWjY3' AND groupData.users.userId = 'pending'.

{
    "_id" : "Au2NH2iMwGfGtzqzH",
    "name" : "Toyota",
    "profileType" : "group",
    "groupData" : {
        "private" : false,
        "users" : [ 
            {
                "userId" : "9qcHtd4sRFZQpPaHD",
                "role" : "admin",
                "addedAt" : ISODate("2020-09-16T17:23:28.266Z")
            }, 
            {
                "userId" : "CnugxoBWs4ox6vG2k",
                "role" : "member",
                "addedAt" : ISODate("2020-09-16T17:23:37.292Z")
            }, 
            {
                "userId" : "aFHJBrKu54y5mWjY3",
                "role" : "pending",
                "addedAt" : ISODate("2020-09-16T17:23:41.878Z")
            }, 
            {
                "userId" : "GoXMTJKCWSpRdyn7c",
                "role" : "member",
                "addedAt" : ISODate("2020-09-16T17:23:51.281Z")
            }
        ]
    }
}

I trying the following:

            const profiles = Profiles.find({
                'groupData.users.userId': this.userId,
                'groupData.users.role': 'pending'
            }).fetch();

But it returns wrong profiles. Thank you!

1

1 Answer 1

1

You can get with elemMatch. But you need to be aware of Positional operator in projection

db.collection.find({
  "groupData.users": {
    "$elemMatch": {
      userId: "aFHJBrKu54y5mWjY3",
      role: "pending"
    }
  }
},
{
  "groupData.users.$": 1
})

Working Mongo playground

Sign up to request clarification or add additional context in comments.

2 Comments

@podeig you are welcome.. Why don't you consider to accept the answer which helps to people who seek this kind of problems
I am so sorry, Varman. I upvoted it but forgot to accept. Sorry :)

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.