9

I want to create a text index for multiple fields and fields of elements in an array. Currently I define the path to the array elements as a string, which works. Is there a way to use an expression just like I can do for simple fields like this:

var textIndex = Builders<Project>.IndexKeys
    .Text(p => p.Name)
    .Text(p => p.Description)
    // This and any other expression I tried does not work
    //.Text(p => p.System.Elements.SelectMany(e => e.Name))
    // But this works fine:
    .Text("system.elements.name");

await collection.Indexes.CreateOneAsync(textIndex);

I'm using mongodb 3.2 and MongoDB.Driver 2.2.2

hansmaad
  • 18,417
  • 9
  • 53
  • 94
  • 4
    As far is 1 know it's not yet supported. There is an open JIRA ticket: https://jira.mongodb.org/browse/CSHARP-1309?jql=text%20~%20%22index%20array%22 – HoefMeistert Sep 12 '16 at 10:11

1 Answers1

0

I came here myself looking for a solution, and your idea seems to work. I'm still just prototyping my code, so it could be better, but what worked for me is:

private static IMongoDatabase db = dataConnector.ConnectDatabase();

private void CreateIndex(string collection)
{
    var CompoundTextIndex = new CreateIndexModel<MyDataModel>
        (Builders<MyDataModel>.IndexKeys
        .Text(x=> x.name)
        .Text(x => x.parentCompany));

    db.GetCollection<MyDataModel>
        (collection).Indexes.CreateOne(CompoundTextIndex);
}
desa
  • 48
  • 8