Mongo中的外键? [英] Foreign keys in mongo?

查看:583
本文介绍了Mongo中的外键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如何我在MongoDB中设计这样一个方案?我认为没有外键!

解决方案

您可能有兴趣使用像Mongoid或MongoMapper这样的ORM。

http://mongoid.org/docs/relations/referenced /1-n.html



在像MongoDB这样的NoSQL数据库中,不存在表,而是文档。文档被分组在集合中。您可以将任何种类的文档与任何种类的数据集中在一个集合中。基本上,在NoSQL数据库中,由您来决定如何组织数据及其关系,如果有的话。



Mongoid和MongoMapper做的是提供你用方便的方法很容易地建立关系。查看我给你的链接并询问任何事情。

编辑:

在mongoid中,你会写你的方案是这样的:

$ p $ class Student
包含Mongoid :: Document

字段:名称
embeds_many:地址
embeds_many:分数
结束

类地址
包含Mongoid :: Document

字段:地址
字段:city
字段:state
字段:postalCode
embedded_in:student
结尾
$ b $类别Score $ b $ include include Mongoid ::文档

belongs_to:课程
字段:成绩,类型:浮点型
嵌入式:学生
结束


课程
包含Mongoid :: Document

字段:名称
has_many:分数
结束

编辑:

 > db.foo.insert({group:phones})
> db.foo.find()
{_id:ObjectId(4df6539ae90592692ccc9940),group:phones}
{_id:ObjectId(4df6540fe90592692ccc9941), :phones}
> db.foo.find({'_ id':ObjectId(4df6539ae90592692ccc9940)})
{_id:ObjectId(4df6539ae90592692ccc9940),group phone}

您可以使用该ObjectId来完成文档之间的关系。


How do I design a scheme such this in MongoDB? I think there are no foreign keys!

解决方案

You may be interested in using a ORM like Mongoid or MongoMapper.

http://mongoid.org/docs/relations/referenced/1-n.html

In a NoSQL database like MongoDB there are not 'tables' but documents. Documents are grouped inside Collections. You can have any kind of document – with any kind of data – in a single collection. Basically, in a NoSQL database it is up to you to decide how to organise the data and its relations, if there are any.

What Mongoid and MongoMapper do is to provide you with convenient methods to set up relations quite easily. Check out the link I gave you and ask any thing.

Edit:

In mongoid you will write your scheme like this:

class Student
  include Mongoid::Document

    field :name
    embeds_many :addresses
    embeds_many :scores    
end

class Address
  include Mongoid::Document

    field :address
    field :city
    field :state
    field :postalCode
    embedded_in :student
end

class Score
  include Mongoid::Document

    belongs_to :course
    field :grade, type: Float
    embedded_in :student
end


class Course
  include Mongoid::Document

  field :name
  has_many :scores  
end

Edit:

> db.foo.insert({group:"phones"})
> db.foo.find()                  
{ "_id" : ObjectId("4df6539ae90592692ccc9940"), "group" : "phones" }
{ "_id" : ObjectId("4df6540fe90592692ccc9941"), "group" : "phones" }
>db.foo.find({'_id':ObjectId("4df6539ae90592692ccc9940")}) 
{ "_id" : ObjectId("4df6539ae90592692ccc9940"), "group" : "phones" }

You can use that ObjectId in order to do relations between documents.

这篇关于Mongo中的外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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