MongoDB C # Driver - execute LINQ "Any" in a serialized dictionary

I have a document type with some attributes, one of which is the dictionary <string, string>.

Serialization and de-sorting seem to work (I can do a search, do CRUD operations, etc.). The problem is that I'm trying to write a method to search for all objects of this type, where the dictionary contains a specific value (id) among its keys.

Request Attempt:

var objectCollection = db.GetCollection<MyClass>("MyClass");

var query = Query<MyClass>.Where(m => m.MyDictionary.Any(k => k.Key == id));

Grade:

public class MyClass
{

    public ObjectId Id { get; set; }
    // ...
    [BsonElement("Dictionary")]
    public Dictionary<string, string> MyDictionary { get; set; }
}

... but I get this exception when building the request:

Any requires that the serializer specified for Dictionary support items by implementing 
MongoDB.Bson.Serialization.IBsonArraySerializer and returning a non-null result. 
MongoDB.Bson.Serialization.Serializers.DictionarySerializer`2[System.String,System.String] 
is the current serializer.

I suspect the problem is that the default serializer for C # does not support this by default. Is there a workaround?

I also tried doing β€œContains” for the string idin the collection Dictionary.Keys, but this givesNotSupportedException: Unable to determine the serialization information for the expression: m.Dictionary.Keys.

+4
1

...

​​ MyClass, , , ( SerializationOptions ).

[BsonElement("Dictionary")]
[BsonDictionaryOptions(DictionaryRepresentation.ArrayOfDocuments)] // Added This!
public Dictionary<string, string> Dictionary { get; set; }

, "k" () "v" ().

:

var query = Query.ElemMatch("Dictionary", Query.EQ("k", id));

, id .

:

+4

Source: https://habr.com/ru/post/1535337/


All Articles