【发布时间】:2018-07-12 12:55:32
【问题描述】:
我有以下情况。我有两个班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";
}
}
序列化为IMongoCollections
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 转换为特定类类型的文档?
【问题讨论】:
-
出于好奇,您尝试过什么?
-
我还在寻找,但我的努力似乎是徒劳的。要么这不是以前提出的问题,要么有一些我无法匹配的措辞来查找有关它的信息。我只是一直在寻找有关“将 BsonDocument 转换为强类型”的帖子。哪个措辞紧密但不是同一个问题。
-
我需要编写一个测试用例来确认,但只要 BsonDocument 反映了被映射类型的属性,C# 驱动程序就会为您处理好。
标签: c# mongodb mongodb-.net-driver