c# - 将存储的 MongoDB 集合文档从 BsonDocument 转换为“MyClass”类型?
问题描述
我有以下情况。我有两节课Person
和Animal
using System;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace MongoTesting.Documents
{
public class Person
{
[BsonId]
[BsonRepresentation(BsonType.String)]
public Guid PersonId { get; set; } = Guid.NewGuid();
public Guid PetId { get; set; } = Guid.Empty;
public string Name { get; set; } = "Person";
}
}
using System;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace MongoTesting.Documents
{
public class Animal
{
[BsonId]
[BsonRepresentation(BsonType.String)]
public Guid AnimalId { get; set; } = Guid.NewGuid();
public bool IsMammal { get; set; }
public string Description { get; set; } = "Animal";
}
}
其中被序列化为IMongoCollection
s
public IMongoCollection<BsonDocument> PersonCollection { get; set; }
public IMongoCollection<BsonDocument> AnimalCollection { get; set; }
...
PersonCollection = Database.GetCollection<BsonDocument>("PersonCollection");
AnimalCollection = Database.GetCollection<BsonDocument>("AnimalCollection");
在这些类型的集合中,IMongoCollection<BsonDocument>
我现在有大量的文档。
我最近一直在重构与 MongoDB 相关的代码和查询。我发现我可以将文档保存到具有强类型文档的集合中,例如我现在有了集合
public IMongoCollection<Person> PersonCollection { get; set; }
public IMongoCollection<Animal> AnimalCollection { get; set; }
我可以在其上轻松执行更清晰、更有意义的查询。
由于这些更改以及已存储在我的集合中的大量文档,我想将集合中的文档从转换BsonDocument
为Person
/文Animal
档。
如何将存储的 MongoDB 集合文档转换BsonDocument
为特定类类型的文档?
解决方案
刚刚对此进行了测试,我可以确认只要属性名称匹配,C# 驱动程序就会默认处理映射。更复杂的情况(如多态)需要更多的工作,但本质上,你可以这样做:
//define the collection and a sample BsonDocument:
var collectionName = "bsonDocs";
var bsonDoc = BsonDocument.Parse("{ \"_id\" : ObjectId(\"5b476c4b7d1c1647b06f8e75\"), \"Detail\" : \"testString1\", }");
//Establish connection to database
var clientInstance = new MongoClient();
var db = clientInstance.GetDatabase("TEST");
//Get the collection as BsonDocuments
var collection = db.GetCollection<BsonDocument>(collectionName);
//Insert a BsonDocument
collection.InsertOne(bsonDoc);
//Get the same collection, this time as your data model type
var modelCollection = db.GetCollection<TestDataModel>(collectionName);
//Query that collection for your data models
var models = modelCollection.AsQueryable().FirstOrDefault();
//Write data models to that same collection
modelCollection.InsertOne(new TestDataModel{Detail = "new Item"});
其中 TestDataModel 是:
class TestDataModel
{
public ObjectId {get;set;}
public string Detail {get;set;}
}