如何最好地在mongodb中存储有关继承的信息? [英] How best to store information about inheritance in mongodb?
问题描述
比方说,我有3种类型的对象:Animal
,Dog
和Poodle
.我想将这些对象中的数据作为文档存储在mongodb中.
Let's say I have 3 types of objects: Animal
, Dog
, and Poodle
. I want to store the data in these objects as documents in mongodb.
假设我的Animal
文档看起来像:
Let's say my document for Animal
looks like:
{
"name": ...
}
我对Dog
的文档如下:
{
"name": ...,
"barkFile": ...
}
我的Poodle
文档如下:
{
"name": ...,
"barkFile": ...,
"haircut": ...
}
在查找有关存储不同类型对象的建议时,几乎每个人似乎都说使用类型字段.这样对不同类型的动物都适用,就像这样:
When looking up suggestions about storing objects of different types, pretty much everyone seems to say use a type field. That would work fine for different types of animals, like this:
{
"_type": "cat",
"name": ...,
"meowFile": ...
}
{
"_type": "dog",
"name": ...,
"barkFile": ...
}
但是它不允许我存储3个继承级别.基本上我想做这样的事情:
But it doesn't allow me to store 3 levels of inheritance. Basically I want to do something like this:
doc1 = {
"_type": "animal",
"name": ...
}
doc2 = {
"_type": "animal.dog",
"name": ...,
"barkFile": ...
}
doc3 = {
"_type": "animal.dog.poodle",
"name": ...,
"barkFile": ...,
"haircut": ...
}
我不想完全像这样做,因为我希望能够做类似db.animals.find({type: 'animal.dog'})
的操作并同时获取doc2和doc3.我宁愿不要重新发明轮子,因此,如果这个问题以前已经解决过(我怀疑已经解决过),我将不胜感激有人将我引向其他人提出的解决方案.谢谢.
I don't want to do it exactly like this, as I want to be able to do something like db.animals.find({type: 'animal.dog'})
and get both doc2 and doc3. I'd rather not reinvent the wheel, so if this problem has been dealt with before (which I suspect it has), I'd appreciate someone directing me towards the solutions other people have come up with. Thanks.
推荐答案
您可以将类型和子类型简单地存储在这样的数组中:
You could simply store the types and subtypes in an array like this:
doc1 = {
"_type": ["animal"],
"name": ...
}
doc2 = {
"_type": ["animal","dog"],
"name": ...,
"barkFile": ...
}
doc3 = {
"_type": ["animal","dog","poodle"],
"name": ...,
"barkFile": ...,
"haircut": ...
}
使用此模型,查询db.data.find({_type:"dog"})
返回doc2和doc3.
Using this model, the query db.data.find({_type:"dog"})
returns both doc2 and doc3.
这篇关于如何最好地在mongodb中存储有关继承的信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!