mongodb Mongo DB中的外键关系
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9939022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Foreign key like relationship in Mongo DB
提问by Lasantha Bandara
How can I implement a foreign key like relationship in Mongo DB?
如何在 Mongo DB 中实现类似外键的关系?
采纳答案by Tats_innit
hiya see this: MongoDB normalization, foreign key and joining&& further http://shop.oreilly.com/product/0636920018391.do===> http://books.google.com/books/about/Document_Design_for_MongoDB.html?id=TbIHkgEACAAJ&redir_esc=y
hiya 看到这个:MongoDB 规范化,外键和加入&& 进一步http://shop.oreilly.com/product/0636920018391.do===> http://books.google.com/books/about/Document_Design_for_MongoDB.html? id=TbIHkgEACAAJ&redir_esc=y
MongoDB doesn't support server side foreign key relationships, normalization is also discouraged. You should embed your child object within parent objects if possible, this will increase performance and make foreign keys totally unnecessary. That said it is not always possible, so there is a special construct called DBRef which allows to reference objects in a different collection. This may be then not so speedy because DB has to make additional queries to read objects but allows for kind of foreign key reference.
Still you will have to handle your references manually. Only while looking up your DBRef you will see if it exists, the DB will not go through all the documents to look for the references and remove them if the target of the reference doesn't exist any more. But I think removing all the references after deleting the book would require a single query per collection, no more, so not that difficult really.
MongoDB 不支持服务器端外键关系,也不鼓励规范化。如果可能,您应该将子对象嵌入到父对象中,这将提高性能并使外键完全不必要。也就是说,这并不总是可行的,因此有一个称为 DBRef 的特殊结构,它允许引用不同集合中的对象。这可能不是那么快,因为 DB 必须进行额外的查询来读取对象,但允许某种外键引用。
您仍然必须手动处理您的参考。只有在查找您的 DBRef 时,您才会看到它是否存在,如果引用的目标不再存在,DB 将不会遍历所有文档来查找引用并删除它们。但我认为在删除这本书后删除所有引用需要对每个集合进行一次查询,没有更多,所以真的没有那么困难。
Edit update
编辑更新
http://levycarneiro.com/tag/mongodb/
http://levycarneiro.com/tag/mongodb/
levycarneiro.com/tag/mongodb [quote] So you create 4 collections: Clients, Suppliers, Employees and Contacts. You connect them all together via a db reference. This acts like a foreign key. But, this is not the mongoDB way to do things. Performance will penalized. [unquote]
levycarneiro.com/tag/mongodb [quote] 所以你创建了 4 个集合:Clients、Suppliers、Employees 和 Contacts。您可以通过 db 引用将它们全部连接在一起。这就像一个外键。但是,这不是 mongoDB 的做事方式。表现将受到惩罚。[取消引用]