1

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 Answers 2

1

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()
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the reply, the problem that I have is that this code is part of an FindAndModify(query, update) statement where query represents my question. I dont see how I convert your solution to a query. (I'm fairly new to mongodb, so forgive me is im asking dumb questions)
Hey yogesh, I tried your solution using the shell and it works! Now I'm having problems converting this to C# (driver 2.0), do you by any chance know how to do that?
@Lale : see here and here. This should help you to convert solution to C#.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.