Find elements in MongoDB that contain at least 3 entries in an array

Viewed 61

I have an array like this one:

let list = [ "cake", "apple", "banana", "flour", "orange", "pasta", "tomato" ]

And I have some documents on a MongoDB collections like these:

{ food: [ "cake", "tomato", "coffee", "fish" ] }
{ food: [ "cake", "tomato", "coffee", "flour" ] }
{ food: [ "cake", "banana", "orange", "flour" ] }
{ food: [ "ravioli", "lemon", "potato", "tea" ] }

I need to query this collection so that only documents that share 3 or more entries of the food array with the list array. So I'd need the query to return:

{ food: [ "cake", "tomato", "coffee", "flour" ] }
{ food: [ "cake", "banana", "orange", "flour" ] }

I googled for an hour without any results that could help me.

1 Answers

You can use this $match. It finds the common elements(food,list), counts how many they are, and keeps document only if those common elements >= 3

{"$match":{"$expr":{"$gte":[{"$size":{"$setIntersection":["$food",list]}},3]}}}]

I tested it and it returned those 2 documents.

Related