简体   繁体   English

MongoDB C#驱动程序:如何确保在数组内容上使用LINQ表达式的索引?

[英]MongoDB C# Driver: How do I ensure an index using LINQ expressions on the contents of an array?

How can I ensure an index using LINQ expressions on the contents of an array using the MongoDB C# driver? 如何使用MongoDB C#驱动程序确保在数组内容上使用LINQ表达式的索引?

I currently have a domain object that looks roughly like this: 我目前有一个看起来像这样的域对象:

public class Team
{
    public Team()
    {
        Members = new List<LazyReference>();
    }

    public MongoDB.Bson.ObjectId Id { get; set; }
    public string DisplayName { get; set; }
    public LazyReference Leader { get; set; }
    public List<LazyReference> Members { get; private set; }
}

public class LazyReference
{
    public MongoDB.Bson.ObjectId Id { get; set; }
}

On my collection, I have initialized a couple of indexes like this: 在我的收藏中,我初始化了几个这样的索引:

collection.EnsureIndex(IndexKeys<Team>.Ascending(t => t.DisplayName), IndexOptions.SetUnique(true));
collection.EnsureIndex(IndexKeys<Team>.Ascending(t => t.Leader.Id), IndexOptions.SetUnique(false));

How can I do the same to ensure a fast index of the Members when looking up by Members[n].Id, where n is any of the members? 如何在成员[n]查询时确保成员的快速索引,我该如何做同样的事情?其中,n是否是任何成员? I am aware that I can create an index as follows, but since this does not use the LINQ expressions, it is not safe for future renames of properties. 我知道我可以创建一个索引如下,但由于这不使用LINQ表达式,因此对于将来的属性重命名是不安全的。

collection.EnsureIndex(new IndexKeysBuilder().Ascending("Members._id"), IndexOptions.SetUnique(false));

I have also tried the following, but it only indexes the index specified: 我也试过以下,但它只索引指定的索引:

collection.EnsureIndex(IndexKeys<Team>.Ascending(t => t.Members[0].Id), IndexOptions.SetUnique(false));

I ended up using the following: 我最终使用了以下内容:

await collection.Indexes.CreateOneAsync(Builders<Team>.IndexKeys.Ascending($"{nameof(Team.Members)}.{nameof(LazyReference.Id)}"), new CreateIndexOptions() { Unique = false });

this protects from property renaming but still not as elegant as Linq. 这可以防止属性重命名,但仍然不如Linq那么优雅。 The above code creates an index like { "Members._id" : 1 } . 上面的代码创建了一个像{ "Members._id" : 1 }这样的索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM