有几种方法可以实现这一点,具体取决于您的非结构化数据在编译时还是运行时已知。
对于编译类型,您可以对数据的投影进行建模并使用投影构建器来指定投影的工作方式
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();