草庐IT

c# - MongoDB C# 驱动程序 : How do I ensure an index using LINQ expressions on the contents of an array?

coder 2023-11-01 原文

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

我目前有一个大致如下所示的领域对象:

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; }
}

在我的收藏中,我已经初始化了几个这样的索引:

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

当通过 Members[n].Id(其中 n 是任何成员)查找时,我如何才能确保成员的快速索引?我知道我可以按如下方式创建索引,但由于这不使用 LINQ 表达式,因此将来对属性重命名是不安全的。

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

我也试过以下,但它只索引指定的索引:

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

最佳答案

我最终使用了以下内容:

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

这可以防止属性重命名,但仍然不如 Linq 优雅。上面的代码创建了一个类似 { "Members._id": 1 } 的索引。

关于c# - MongoDB C# 驱动程序 : How do I ensure an index using LINQ expressions on the contents of an array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18577697/

有关c# - MongoDB C# 驱动程序 : How do I ensure an index using LINQ expressions on the contents of an array?的更多相关文章

随机推荐