Mongodb query documents where nested array is equal or subset of fixed array

790 Views Asked by At

I keep banging my head against the wall trying to solve the following problem (I'm using the new c# 2.0 driver):

The idea is to return all docs where the nested array is equal or a subset of a fixed array. Example:

Fixed array: [ "A", "B", "C" ]

container docs:

{
    container1 { Name: "name1", Tags: [ "A", "B" ] },
    container2 { Name: "name4", Tags: [ "A", "B", "C", "D" ] },
    container3 { Name: "name2", Tags: [ "A" ] },
    container4 { Name: "name3", Tags: [ "A", "B", "C" ] }
}

Based on the above data, the result should be:

{
    container1 { Name: "name1", Tags: [ "A", "B" ] },
    container3 { Name: "name2", Tags: [ "A" ] },
    container4 { Name: "name3", Tags: [ "A", "B", "C" ] }
}

Notice how container2 was not part of the result set since [ "A", "B", "C", "D" ] is not a subset nor equal to [ "A", "B", "C" ]

Please if you have a non-2.0-C#-driver solution post it here anyways. It will help.

Much appreciated!!!

2

There are 2 best solutions below

3
On BEST ANSWER

Use mongo Set Operator using $setIsSubset in aggregation you will get your result, check following query :

db.collectionName.aggregate({
  "$project": {
    "Name": 1,
    "Tags": 1,
    "match": {
      "$setIsSubset": ["$Tags", ["A", "B", "C"]] //check Tags is subset of given array in your case array is ["A","B","C"]
    }
  }
}, {
  "$match": {
    "match": true // return only those matched true values
  }
}, {
  "$project": {
    "Name": 1,
    "Tags": 1
  }
}).pretty()
0
On

Try

db.collectionName.find({$or:[{Tags: ["A","B","C"]},{Tags: {$in:["A","B","C"], $not : {$all : ["A","B","C"]}}}]})

Explanation:

$in gives all the documents containing at least one element of the given set; $all gives the supersets of the given set, including the set itself.

What you want to find is the given set or any set which includes at least one element but not others