[SOLVED] Find values of an array in another array

This is probably going to sound nuts, so forgive me now.

I have a collection where I setup a group of users. I just use the user _ids in this collection.

{
	"_id" : "qT9BpAh4AHXhDtaNj",
	"groupName" : "Full Group",
	"usersInGroup" : [
		"mrk2oWeLX4fG26eF5",
		"5vhoJ2jjgHEKo7WiR"
	],
	"active" : true
}

These groups can of course have many users. Now, I have a collection that can add groups to be allowed to view items from the collection.

So, I create something like:

"associations" : {
		"allowOverride" : true,
		"userGroupAssoc" : [
                       "Full Group",
                      "My Test Group"
               ]
	},

I go grab my users groups with a simple query based on my _id. No biggie there, and then have to use that in another query against my main collection. Right now, I’m adding my users groups to an array, then doing the following:

When I go to query my collection I did this, and forgive me because I know it’s ugly:

Calls.find({
    $or: [
        { "associations.userGroupAssoc": "Full Group" }, 
        { "associations:userGroupAssoc": "My Test Group" }
    ]
});

Of course the above is just manually querying. I really need to be able to get the group values from the array into this query instead, but without knowing how many there may be I’m not sure how.

I’m probably overthinking it.

This works, but I won’t actually know how many groups may be associated to my collection, nor how many groups a user may be associated to.

So is there a way to do this query differently? Basically I’m going to be looking for a value in an array comparred to another array of values. In each, only one has to match.

Any help is greatly appreciated.

Also, my collection is not set in stone yet, so if there’s a better way to structure, I’m open to ideas.

The $in operator should help with this. Check https://docs.mongodb.com/manual/reference/operator/query/in/

1 Like

Thanks, didn’t realize that an array in a collection, could use $in to match any item in an array. That’s awesome! And, I was over complicating it. Thanks @hluz

1 Like