How to create a MongoDB MultiKey index for an attribute of elements in a .NET Driver array

I have a MongoDB "foos" collection containing elements, each of which has an array of "bars". That is, "foo" has the following scheme:

{
    "id": UUID
    "name": string
    ...
    "bars": [
        "id": UUID
        "key": string
        ...
    ]
}

I need to create an index by name and bar.key using the MongoDB C # .NET Mongo driver.

I suggested that I could use the Linq Select function to do this as follows:

Indexes.Add(Context.Collection<FooDocument>().Indexes.CreateOne(
    Builders<FooDocument>.IndexKeys
        .Descending(x => x.Bars.Select(y => y.Key))));

However, this throws an InvalidOperationException:

System.InvalidOperationException: "Unable to determine serialization information for x => x.Bars.Select (y => y.Id). '

The Mongo MultiKey index documentation shows how to create such an index using simple dot notation, i.e.

db.foos.createIndex( { "name": 1, "bars.key": 1 } )

MongoDB, , , Linq, , .

MongoDB.NET, Linq?

+6
3

, #

var indexDefinition = Builders<FooDocument>.IndexKeys.Combine(
    Builders<FooDocument>.IndexKeys.Ascending(f => f.Key1),
    Builders<FooDocument>.IndexKeys.Ascending(f => f.Key2));

await collection.Indexes.CreateOneAsync(indexDefinition); 

UPDATE

, , , "-1" , . github .

var indexDefinition = Builders<FooDocument>.IndexKeys.Combine(
    Builders<FooDocument>.IndexKeys.Ascending(f => f.Key1),
    Builders<FooDocument>.IndexKeys.Ascending(f => f.Key2[-1].Key));

await collection.Indexes.CreateOneAsync(indexDefinition); 

"- 1" mongodb # , "$" (proof). , :

{ "Key1": 1, "Key2.$.Key": 1 }

, ( ). : "$" ) . , mongodb, . - "-2" .

var indexDefinition = Builders<FooDocument>.IndexKeys.Combine(
    Builders<FooDocument>.IndexKeys.Ascending(f => f.Key1),
    Builders<FooDocument>.IndexKeys.Ascending(f => f.Key2[-2].Key));

await collection.Indexes.CreateOneAsync(indexDefinition); 

, :

{ "Key1": 1, "Key2.Key": 1 }

, , Linq, M #.

, , - #, Linq

await collection.Indexes.CreateOneAsync(new BsonDocument {{"name", 1}, {"bars.key", 1}});
+3

, #, . , - - JIRA, , , .

+2

You can create a row index and use nameof()in C # 6:

Indexes.Add(Context.Collection<FooDocument>().Indexes.CreateOne($"{nameof(FooDocument.Bars)}.{nameof(Bars.Key)}"));
+2
source

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


All Articles