2

I have a defined collection in Mongo that is a list of "supported" features. In order for an item from another collection to be considered "compatible", I need to take that item's list of features and see if all of them are in the given list. I have queried the supported features collection for the list of features already and I have them in a list.

For example, my list contains [A, B, C, D, E]
If my item has [A, B], it should be returned, but if it has [A, B, F], it should not. The $in operator states:

"If the field holds an array, then the $in operator selects the documents whose field holds an array that contains at least one element that matches a value in the specified array"

The $all operator states:

"The $all operator selects the documents where the value of a field is an array that contains all the specified elements."

My problem is that the item doesn't have the full set of features for the $all command, and I don't want it to match on a single element for the $in command. My query looks something like this (because I have already retrieved the list of compatible functions from the functions collection):

db.myColl.find({"compatibility": {"$in": ["A","B","C","D","E","F"]}})    

or

db.myColl.find({"compatibility": {"$all": ["A","B","C","D","E","F"]}})

what I think I need is something that effectively reverses the query and says something like this (I know it's not valid, I'm just trying to make a point):

db.myColl.find({["A","B","C","D","E","F"]: {"$all": "compatibility"}})

Any thoughts?

Andrew Schuster
  • 3,229
  • 2
  • 21
  • 32
  • I think it will be a lot easier if you share some schema information with concrete examples - you mention multiple collections but don't show schemas for either, and your examples don't match (first example compares a list (from where?) of [A,B,C,D,E] vs [A,B] and [A,B,F], second example is [A,B,C,D,E,F] against something else. I'd give concrete example documents and examples of where you want it to match and not match. – John Petrone May 23 '14 at 22:00
  • possible duplicate of [Check if every element in array matches condition](http://stackoverflow.com/questions/23595023/check-if-every-element-in-array-matches-condition) – Neil Lunn May 23 '14 at 23:00

1 Answers1

1

I recently had a very similar issue and found the solution:

db.myColl.find({"compatibility":{$not:{$elemMatch:{$nin:["A","B","C","D","E","F"]}}}})

While I'm not an expert in mongodb, it seems like they should add a primitive for this operation.

Good luck!

dsmith
  • 154
  • 5
  • That did it - thanks! Sorry if I duplicated another question. I swear I searched for every term I could think of to represent the problem and could never get a satisfactory result! – dragonfly30 May 27 '14 at 18:29