将MongoDB集合检索为`IMongoCollection序列 `在.NET驱动程序中

问题描述 投票:1回答:2

IMongoDatabase.ListCollections将光标移回BsonDocument。为什么不将光标返回IMongoCollection<T>呢?

我试图编写一个通用的GetCollection方法来检索只给出文档类型的集合,如下所示:

private IMongoCollection<T> GetCollection<T>()
{
    var client = new MongoClient("connectionString");
    var db = client.GetDatabase("dbName");
    var coll = db.ListCollectionsAsync().Result.ToListAsync().Result
        // Find collection of document of type T
        // Collection is a BsonDocument instead
        .Find(collection => typeof(collection) == typeof(T));

    return coll;
}
mongodb mongodb-.net-driver
2个回答
0
投票

驱动程序不知道集合中的文档类型,这就是它需要类型参数T的原因。 MongoDB本身并不知道数据库中的文档如何映射到应用程序中的类型。

无法连接到“通用”MongoDB部署,只需发现其中的集合和类型即可。这是您需要编写的代码,可能不会很好,因为它将类似于试验和错误。

如果您只是尝试创建工厂类型,则需要在调用GetCollection<T>之前构建集合的支持列表。

您可以尝试使用类型名称作为集合名称。这将使集合名称可重复(除非更改类型名称)。但我从来没有对它进行测试,它可能在现实世界中有一些特质。

public class MyDatabase
{
    private readonly IMongoClient _client;
    public MyDatabase(string connectionString)
    {
        _client = new MongoClient(connectionString);
    }

    public IMongoCollection<T> GetCollection<T>()
    {
        var db = _client.GetDatabase("dbName");
        return db.GetCollection<T>(typeof(T).Name);
    }
}

如果你更喜欢集合名称是多元化的,像Humanizer这样的东西可以帮助那里。

我通常更喜欢创建一个将集合作为类中的字段的类型。例如:

public class MyDatabase
{
    private readonly IMongoClient _client;
    public IMongoCollection<Foo> Foos { get; }
    public IMongoCollection<Bar> Bars { get; }
    public MyDatabase(string connectionString)
    {
        _client = new MongoClient(connectionString);
        var db = _client.GetDatabase("myDb");
        Foos = db.GetCollection<Foo>("foos");
        Bars = db.GetCollection<Bar>("bars");
    }
}

0
投票

MongoDB集合具有灵活的方案,允许您将任何具有任何结构的文档插入到集合中。例如,我们可以将以下3个对象插入到test集合中,它是有效的:

> db.test.insertMany([{one: 1}, {two:2}, {three: 3}])
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("5c87c954ed372bf469367e57"),
                ObjectId("5c87c954ed372bf469367e58"),
                ObjectId("5c87c954ed372bf469367e59")
        ]
}
> db.test.find().pretty()
{ "_id" : ObjectId("5c87c954ed372bf469367e57"), "one" : 1 }
{ "_id" : ObjectId("5c87c954ed372bf469367e58"), "two" : 2 }
{ "_id" : ObjectId("5c87c954ed372bf469367e59"), "three" : 3 }

因此,您无法将MongoDB集合映射到.NET类型,因为集合不知道该类型。

© www.soinside.com 2019 - 2024. All rights reserved.