1

With the following structure:

class A
{
    ...
    List<B> L;
}

class B
{
    ...
    string S;
}

and a collection of objects A, is it possible to create an index on the S fields?


Update: The solution proposed in the comments does NOT work:

public class A
{
    public List<B> L;
    public A()
    {
        L = new List<B>();
    }
}

public class B
{
    public string S;
}

and index creation:

MongoCollection.Indexes.CreateOne(new BsonDocument {{ "B.S", 1}});

yields:

enter image description here

only the _id field gets indexed, but B.S is not.

8
  • Possible duplicate of How to create MongoDB MultiKey index on attribute of items in an array .NET Driver Commented Mar 5, 2018 at 4:05
  • I saw this one, but I don't see how my question relates to multi-key Commented Mar 5, 2018 at 4:06
  • I assume you plan to ignore the fact that it shows you how to index an array item's value then?: await collection.Indexes.CreateOneAsync(new BsonDocument {{"name", 1}, {"bars.key", 1}}); Commented Mar 5, 2018 at 4:07
  • Or this also shows the same thing albeit for an older version. Commented Mar 5, 2018 at 4:14
  • You mean that new BsonDocument {{"B.S", 1}} would work? Commented Mar 5, 2018 at 4:15

1 Answer 1

2

The last time I checked (mid-late last year), a => a.L[-1].S syntax did not work to create an index, so I do not believe there is a LINQ way of achieving this at the moment.

In my own project, I'm using code similar to this:

myCollection.Indexes
    .CreateOne(Builders<A>.IndexKeys
        .Ascending("L.S"));

This will create an index using the array items.

Sign up to request clarification or add additional context in comments.

3 Comments

Can you check that the index is really built? on my end when I look I don't see an index created on that collection (using Studio 3T)
You tried B.S, not L.S - B is your class name, not your property name.
I just found my own answer from a Google search whilst looking for something else.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.