将存储的 MongoDB collection 文档从 BsonDocument 转换为 "MyClass" 类型?

Converting stored MongoDB collection documents from BsonDocument to "MyClass" type?

我有以下情况。我有两个 classes PersonAnimal

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";
    }
}

被序列化为IMongoCollections

public IMongoCollection<BsonDocument> PersonCollection { get; set; }
public IMongoCollection<BsonDocument> AnimalCollection { get; set; }
...
PersonCollection = Database.GetCollection<BsonDocument>("PersonCollection");
AnimalCollection = Database.GetCollection<BsonDocument>("AnimalCollection");

在这些 collection 类型 IMongoCollection<BsonDocument> 中,我现在有大量文档。


我最近一直在重构与 MongoDB 相关的代码和查询。我发现我可以使用强类型文档将文档保存到 collections 中,例如我现在有 collections

public IMongoCollection<Person> PersonCollection { get; set; }
public IMongoCollection<Animal> AnimalCollection { get; set; }

我可以轻松地执行更清晰、更有意义的查询。


由于这些更改以及我的 collection 中已经存储了大量文档,我想将 collection 中的文档从 BsonDocument 转换为 Person/Animal 个文档。

如何将存储的 MongoDB collection 文档从 BsonDocument 转换为特定 class 类型的文档?


刚刚对此进行了测试,我可以确认只要 属性 名称匹配,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;}
}