Create a text index for fields in array using an expression
Asked Answered
M

1

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

Morganmorgana answered 1/2, 2016 at 15:45 Comment(1)
As far is 1 know it's not yet supported. There is an open JIRA ticket: jira.mongodb.org/browse/…Pylorus
I
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);
}
Irksome answered 2/11, 2021 at 9:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.