【问题标题】:Read Specific field values from MongodbC#从 MongodbC# 读取特定字段值
【发布时间】:2018-04-09 18:11:51
【问题描述】:

最近我开始使用 MongoDB。我必须使用 mongodb C# 驱动程序从 mongodb 读取特定字段(列)。这意味着无论值如何,我都必须读取特定字段。我只需要指定字段。我有非结构化我的数据库中的数据。所以我的项目中没有模型类。

我从 C# 库中使用 Getcollection 阅读了 Collection。然后在我坚持这个任务之后。

我该如何实现?

【问题讨论】:

    标签: mongodb mongodb-query mongodb-.net-driver mongodb-csharp-2.0


    【解决方案1】:

    有几种方法可以实现这一点,具体取决于您的非结构化数据在编译时还是运行时已知。

    对于编译类型,您可以对数据的投影进行建模并使用投影构建器来指定投影的工作方式

    var collection = database.GetCollection<Customer>("customers");
    
    var document = new Customer(){Name = "Joe Bloggs", Age = 30, Address = "York"};
    collection.InsertOne(document);
    
    var projection = Builders<Customer>
                        .Projection
                        .Include(x => x.Id).Include(x => x.Age);
    
    var customerProjection = await collection.Find(x => true)
                        .Project<CustomerProjection>(projection)
                        .FirstAsync();
    

    上面我们将返回类型指定为通用参数,但如果我们省略它,我们将返回一个BsonDocument,这取决于您的使用情况

    var bsonDocument = await collection.Find(x => true)
                        .Project(projection)
                        .FirstAsync();
    

    我们也可以使用 linq 表达式达到同样的效果:

    var projection = await collection.Find(x => true)
        .Project(x => new {x.Id, x.Age}).FirstAsync();
    

    这将导致返回一个带有 Id 和 Age 的异常类型。

    但是,如果我们在编译时不知道数据并且在运行时基于魔术字符串的字段,那么您需要将 BsonDocument 传递给 GetCollection 方法:

    var collection = database.GetCollection<BsonDocument>("customers");
    

    您现在可以使用上述两种方法来投影 bson 文档,但这将基于每个字段。

    但是,我建议您尝试使用项目构建器,因为它会让您的生活更轻松:

    var projectionDefinition = Builders<BsonDocument>.Projection
                                            .Include("age")
                                            .Exclude("_id");
    
    var projection = await collection.Find(x => true)
                        .Project(projectionDefinition)
                        .FirstAsync();
    

    【讨论】:

    • 这是一个很好的解释,但我的问题是我没有合适的模型,为什么因为我的 mongodb 文档包含不同文档的不同字段。所以我无法预测确切的字段。所以我正在阅读集合Bson Document.Like var collection = _dbContext._database.GetCollection("CarModel");
    • 您必须对要查询和投影的数据有所了解吗?即使是用户传入数据
    • 如果字段为空或 Projection(Include) 中不存在,我需要返回非空字段值或字符串“未指定”。现在如果它不显示字段名称不存在该字段
    • 那你不知道字段名吗?
    • 您需要使用 Exists("...") 运算符进行查询 - docs.mongodb.com/manual/reference/operator/query/exists
    猜你喜欢
    • 1970-01-01
    • 2019-04-19
    • 2016-02-24
    • 2022-10-22
    • 2021-02-04
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    相关资源
    最近更新 更多