MongoEngine:EmbeddedDocument v/s. ReferenceField [英] MongoEngine: EmbeddedDocument v/s. ReferenceField

查看:76
本文介绍了MongoEngine:EmbeddedDocument v/s. ReferenceField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

EmbeddedDocument将允许将文档存储在另一个文档中,而RefereneField仅存储其引用.但是,他们正在实现类似的目标.他们有特定的用例吗?

PS: 在SO上已经有一个问题,但是没有好的答案.

解决方案

答案确实取决于要对存储在mongodb中的数据进行何种处理.重要的是要记住,ReferenceField将指向mongodb中另一个集合中的文档,而EmbeddedDocument则存储在同一集合中的同一文档中.

考虑以下模式:

Person
    -> name
    -> address

Address
    -> street
    -> city
    -> country

如果您希望每个人只有一个地址,并且每个地址都只与一个人关联(一对一关系),并且通常要在数据库中查询一个或多个Person文档,则Person.address字段应为EmbeddedDocumentField.

如果您希望每个人都有一个以上的地址,但每个地址仅与一个人相关联(一对多关系),而您仍然主要查询一个人,则可以使用EmbeddedDocumentListField

如果您希望每个人都有一个以上的地址,并且每个地址将与许多人相关联(多对多关系),则可能应该使用ReferenceField.

但是,即使您是一对一或一对多的,如果Address是您感兴趣的数据模型的一部分,那么将其存储在自己的集合中可能是有利的,因为它使聚合和索引编制更加容易.

要考虑的另一点是,除非您转身它会关闭,当您检索文档时,mongoengine会取消对每个ReferenceField的引用-这可能会引入很多ReferenceField或引用非常大的文档而导致性能下降.

EmbeddedDocument will allow to store a document inside another document, while RefereneField just stores it's reference. But, they're achieving a similar goal. Do they have specific use cases?

PS: There's already a question on SO, but no good answers.

解决方案

The answer to this really depends on what intend to do with the data you are storing in mongodb. It is important to remember that a ReferenceField will point to a document in another collection in mongodb, whereas an EmbeddedDocument is stored in the same document in the same collection.

Consider this schema:

Person
    -> name
    -> address

Address
    -> street
    -> city
    -> country

If you expect every person to have only one address and each address to only be associated with one person (a one-to-one relationship) and you are generally going to query the database for one or more Person documents then the Person.address field should be EmbeddedDocumentField.

If you expect every person to have more than one address but each address will only be associated to one person (a one-to-many relationship) and you will still mainly query for a Person then you can use an EmbeddedDocumentListField.

If you expect every person to have more than one address and each address will be associated with many people (a many-to-many relationship) you probably should use ReferenceField.

However, even if you are one-to-one or one-to-many, if the Address is part of your data model that is of interest then it may be advantageous to have it stored in it's own collection because it makes aggregation and indexing easier.

One other point to consider is that unless you turn it off mongoengine will de-reference every ReferenceFieldwhen you retrieve a document - this might introduce performance penalties with lots of ReferenceField or references to very large documents.

这篇关于MongoEngine:EmbeddedDocument v/s. ReferenceField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆