简体   繁体   中英

How to perform a $setIsSubset on MongoDB using C# driver?

I am trying to use $setIsSubset operator in MongoDB.

Documentation says I should wrote this :

var values = Enumerable.Range(0, 10).ToArray();
var result = myCollection.Find(x => x.ExternalKeys.IsSubsetOf(values)).ToList();

However, I got the following exception :

An unhandled exception of type 'System.ArgumentException' occurred in MongoDB.Driver.dll

Additional information: Unsupported filter: {myCollection}{ExternalKeys}.IsSubsetOf(value(System.Int32[])).

ExternalKeys property is declared as Hashset<int>

I am using MongoDB 3.4 and C# Driver 2.4.4 which AFAIK are latest versions.

You would actually want $in here for "at least one of" [40, 30, 20] to match in the target array. This is done with AnyIn()

myCollection.Find(
  Builders<BsonDocument>.Filter.AnyIn( x => x.ExternalKeys, new[] { 40, 30, 20 } )
).ToList();

$in is not just for arrays but is essentially a list of possible values that can match a property. It's just that MongoDB treats an array as matching "any of it's values" as well.

So that's actually what you are looking for in what you are calling a "subset", since the target is a "subset" of what it is being compared to where any element intersects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM