从 MongodbC 读取特定字段值#

Read Specific field values from MongodbC#

最近我开始使用 MongoDB.I have to read specific fields (columns) from mongodb using mongodb C# driver.That 意味着无论如何我都必须读取特定字段values.i 只需要指定 fields.I 在我的 db.so 中有非结构化数据 我在我的项目中没有模型 class。

在坚持完成此任务后,我阅读了 C# library.then 中使用 Getcollection<> 的集合。

我怎样才能实现?

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

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

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();

上面我们将 return 类型指定为通用参数,但如果我们省略它,那么我们将 returned a 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();

这将导致 return 具有 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();