将存储的MongoDB集合文档从BsonDocument转换为“ MyClass”类型?

时间:2018-07-12 12:55:32

标签: c# mongodb mongodb-.net-driver

我有以下情况。我有两个班级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";
    }
}

哪些序列化为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文档。 / p>

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


1 个答案:

答案 0 :(得分:1)

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