-
Type: New Feature
-
Resolution: Unresolved
-
Priority: Major - P3
-
None
-
Affects Version/s: None
-
Component/s: Querying
-
Labels:None
-
Query Optimization
Using the $in and $all operators to query array fields cover a lot of ground, but when you want query for documents where the array holds at least 4 values, or exactly 8, then MongoDB is missing a useful operator.
Let’s take a simple example. You have a collection of Customers, and each customer document has a purchasedProducts field, which is an array of ObjectId’s (references to all products the customer have purchased). Now, for a marketing campaign you want to find all your customers who have purchased at least 3 out of a set of 10 selected products, in order to send a message to these customers.
In this scenario, the $in operator won’t do, because it would give you all customers who have purchased at least one of the products. The $all operator won’t work either, because it would only give you the customers who have purchased all 10 products in the set. In this scenario a $some operator would come in handy.
As a suggestion, the $some operator could take an array with two items - the first item being an array of values to match against and the second item being an object declaring the condition for a match.
/* * Example of a $some operator where the document would match if purchasedDocuments * contain at least two of the three provided ObjectIds */ db.collection.find({ purchasedProducts: { $some: [[ObjectId('ID1'), ObjectId('ID2'), ObjectId('ID3')], { $gte: 2 }] } })
Using an aggregation pipeline we get access to the tools we need to create the equivalent of a $some operator, as I've outlined in this Medium story but it gets quite verbose and it would be really convenient to have it available as regular query operator.
- is related to
-
SERVER-46788 Suggestion: alias $any to $in
- Backlog