我们正在为我们的 C#.NET 项目在 Mongo DB 上做一个小峰值,看看它是否适合我们,我在 samus 的 mongodb-csharp 驱动程序上遇到了一个小问题,我不确定如何实现.
给定以下简化模型:
public class Campaign
{
public string Name { get; set; }
public IEnumerable<Placement> Placements { get; set; }
}
public class Placement
{
public string Name { get; set; }
//this should be a reference rather than included in the collection
public Site Site { get; set; }
}
//this should be its own collection, and not embedded anywhere
public class Site
{
public string Name { get; set; }
}
正如上面的评论所暗示的,我们试图弄清楚如何将 Site 保存为引用类型而不是嵌入到 Placement 中。站点是它自己的顶级集合,独立于每个活动而变化。
理想情况下,我想使用 MongoConfigurationBuilder 来执行此操作,而不必修改我的 POCO。我似乎找不到任何关于如何完成的文档。
我希望它会像这样简单:
var config = new MongoConfigurationBuilder();
config.Mapping(mapping =>
{
//maybe some more configuration here?
mapping.Map<Site>();
mapping.Map<Campaign>();
});
但是当我使用以下代码时,这仍然是嵌入站点:
var db = mongo.GetDatabase("foo");
var campaignCollection = db.GetCollection<Campaign>();
var siteCollection = db.GetCollection<Site>();
var firstSite = new Site{Name = "first site"};
var secondSite = new Site{Name = "second site"};
var firstCampaign = new Campaign
{
Name = "first campaign",
Placements = new List<Placement>
{
new Placement{Name = "first placement", Site = firstSite},
new Placement{Name = "second placement", Site = secondSite}
}
};
siteCollection.Save(firstSite);
siteCollection.Save(secondSite);
campaignCollection.Save(firstCampaign);
这给了我们:
{ "_id" : ObjectId("4ca9f1db54730000000010cb"),
"Name" : "first campaign",
"Placements" : [
{
"Name" : "first placement",
"Site" : { "Name" : "first site" }
},
{
"Name" : "second placement",
"Site" : { "Name" : "second site" }
}
]}
{ "_id" : ObjectId("4ca9f1db54730000000010c9"), "Name" : "first site" }
{ "_id" : ObjectId("4ca9f1db54730000000010ca"), "Name" : "second site" }
而我们想要的东西更像:
{ "_id" : ObjectId("4ca9f1db54730000000010cb"),
"Name" : "first campaign",
"Placements" : [
{
"Name" : "first placement",
"Site" : ObjectId("4ca9f1db54730000000010c9")
},
{
"Name" : "second placement",
"Site" : ObjectId("4ca9f1db54730000000010ca")
}
]}
{ "_id" : ObjectId("4ca9f1db54730000000010c9"), "Name" : "first site" }
{ "_id" : ObjectId("4ca9f1db54730000000010ca"), "Name" : "second site" }
我不确定这是否是我们最终得到的确切文件,但你明白了。
我觉得好像我遗漏了一些明显的东西,但是没有更好的关于驱动程序这方面的文档,我有点在黑暗中拍摄。我什至查看了源代码中的测试,但无法弄清楚。
有谁知道如何做到这一点?是否可以?