作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我需要存储这个类的一些对象:
public class Category{
public ObjectId Id {get;set;}
public string Name {get;set;}
public string Description {get;set;}
public List<Product> Products {get;set;}
}
public class Product{
public ObjectId Id {get;set;}
public string Name {get;set;}
public string Description {get;set;}
public decimal Price {get;set;}
}
当我使用 NoRM 并存储一个类别对象时mongo.GetCollection().Insert(类别);我可以在 mongo shell 中看到:
db.Category.find()
{ "_id" : ObjectId("82bbbf0179eae0141d020000"), "Name" : "Test products", "Descr
iption" : "This is test category", "Products" : [
{
"_id" : ObjectId("81bbbf0179eae0141d000000"),
"Name" : "Product1",
"Description" : "first product",
"Price" : {
}
},
{
"_id" : ObjectId("82bbbf0179eae0141d010000"),
"Name" : "Product2",
"Description" : "second product",
"Price" : {
}
}
] }
我能否将类别和产品对象存储在不同的集合中,并且在不更改类代码的情况下仅在类别记录中引用产品? (就像 NHibernate 那样)
最佳答案
不,你不能。至少不会自动。
SQL 数据库最适合在多个表中存储规范化 数据。表之间的关系由外键关系定义。 NHibernate 使用这些外键关系将对象映射到多个表。
MongoDB 适用于存储文档。这些文档通常是数据的非规范化表示。这个想法是将相关数据存储在单个文档中,而不是多个表中。由于这种理念,MongoDB 不需要外键概念或加入集合的能力。
理论上,NoRM 可以在未来支持此类功能,但这将违背文档数据库的精神。所以它不太可能永远得到支持。
您可以告诉 NoRM 在保存类别时通过应用 MongoIgnore
属性跳过 Products
属性。然后将产品手动存储在单独的集合中,连同对该类别的“引用”。您可以使用自定义集合自动跟踪产品类别。代码看起来像这样:
public class ProductCollection : Collection<Product>
{
private Category owner;
public ProductCollection(Category owner)
{
// Remember who 'owns' the products in this collection.
this.owner = owner;
}
protected override void InsertItem(int index, Product item)
{
// Tell the product to which category it belongs.
item.CategoryId = this.owner.Id;
base.InsertItem(index, item);
}
// Override other methods using the same pattern.
}
public class Category
{
public Category()
{
this.Id = ObjectId.NewObjectId();
this.Products = new ProductCollection(this);
}
public ObjectId Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
[MongoIgnore]
public ProductCollection Products { get; private set; }
}
public class Product
{
public ObjectId Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public ObjectId CategoryId { get; set; }
}
现在您可以将类别存储在一个集合中,将产品存储在另一个集合中。 CategoryId
属性将指示产品所属的类别。
关于mongodb - 如何将嵌套对象存储在不同的 mongodb 集合中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3546164/
我是一名优秀的程序员,十分优秀!