Match all array elements in an array of arrays with $ all in MongoDB

I have a document that consists of the following documents:

{ "f" : [ [ 1, 2, 3], [4, 5, 6] ] } // should match because of [1, 2, 3]
{ "f" : [ [ 2, 1, 3], [4, 5, 6] ] } // should match because of [2, 1, 3]
{ "f" : [ [ 1, 2, 4], [4, 5, 6] ] } // should NOT match

In this collection, I want to match documents that have an array containing 1, 2, and 3 in one of the arrays of the "f" field.

What I have tried so far:

db.mytest.find({ f: { $elemMatch: { $all: [1,2,3] } } } )

I expect this request to work, but I do not understand why this is not so. I do not agree with the documents.

db.mytest.find({ f: { $elemMatch: { $elemMatch: { $all: [1,2,3] } } } })

This also does not work.

db.mytest.find({ f: { $all: [[1,2,3]] } })

This works, but the elements must be in the exact order. I want to be able to match when the input array is 2, 1, 3. One of the possible solutions is to always store the elements in ascending order and use this query.

db.mytest.find({ f: { $elemMatch: { $elemMatch: { $in: [1, 2, 3] } } } })

This works, but it matches all documents containing any of 1, 2, or 3. I only need documents that contain exactly 1, 2, and 3 in one array.

, ?

+4
3

, . ( ), .

  • Project , "f" .
  • unwind "f" , .
  • match , "f" .
  • Project .

:

db.mytest.aggregate([
{$project:{"temp":"$f","f":1}},    // maintain a temporary variable for projection
{$unwind:"$f"},                    // f:[1,2,3] f:[4,5,6] become separate records.
{$match:{"f":{$all:[1,2,3]}}},     // use $all to match all the elements. 
{$project:{"f":"$temp"}}           // project the temporary variable.
])
+2

, f [1, 2, 3]. db.mytest.find({f: {$in: [[1, 2, 3]]}}).

, , ( Python, itertools.permutations ) $in [[1, 2, 3], [2, 1, 3], ...], .

+1

How to generate all permutations of your array and use in your request? something like that:

db.mytest.find({$or : [{f: {$all : [[1,2,3]] }}, {f: {$all : [[2,1,3]]}}, {f: {$all: [[3,1,2]]}}]})

Perhaps this is not an effective way.

+1
source

All Articles