몽고의 외래 키?
MongoDB에서 이와 같은 체계를 어떻게 설계합니까? 외래 키가 없다고 생각합니다!
Mongoid 또는 MongoMapper와 같은 ORM을 사용하는 데 관심이있을 수 있습니다.
http://mongoid.org/docs/relations/referenced/1-n.html
MongoDB와 같은 NoSQL 데이터베이스에는 '테이블'이 아니라 문서가 있습니다. 문서는 컬렉션 내에 그룹화됩니다. 모든 종류의 데이터가 포함 된 모든 종류의 문서를 단일 컬렉션에 포함 할 수 있습니다. 기본적으로 NoSQL 데이터베이스에서 데이터와 그 관계를 구성하는 방법을 결정하는 것은 사용자에게 달려 있습니다.
Mongoid와 MongoMapper가하는 일은 관계를 아주 쉽게 설정할 수있는 편리한 방법을 제공하는 것입니다. 내가 준 링크를 확인하고 무엇이든 물어보십시오.
편집하다:
mongoid에서는 다음과 같이 계획을 작성합니다.
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
편집하다:
> 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" }
문서 간의 관계를 수행하기 위해 해당 ObjectId를 사용할 수 있습니다.
mongodb에서 이와 같은 테이블을 디자인하는 방법은 무엇입니까?
먼저 몇 가지 명명 규칙을 명확히합니다. MongoDB를이 사용하는 collections
대신 tables
.
외래 키가 없다고 생각합니다!
다음 모델을 사용하십시오.
student
{
_id: ObjectId(...),
name: 'Jane',
courses: [
{ course: 'bio101', mark: 85 },
{ course: 'chem101', mark: 89 }
]
}
course
{
_id: 'bio101',
name: 'Biology 101',
description: 'Introduction to biology'
}
분명히 Jane의 코스 목록은 특정 코스를 가리 킵니다. 데이터베이스는 시스템에 어떠한 제약도 적용하지 않으므로 ( 예 : 외래 키 제약 ) "계단식 삭제"또는 "계단식 업데이트"가 없습니다. 그러나 데이터베이스에는 올바른 정보가 포함되어 있습니다.
또한 MongoDB에는 이러한 참조 생성을 표준화 하는 데 도움 이되는 DBRef 표준 이 있습니다. 실제로 해당 링크를 살펴보면 유사한 예가 있습니다.
이 작업을 어떻게 해결할 수 있습니까?
To be clear, MongoDB is not relational. There is no standard "normal form". You should model your database appropriate to the data you store and the queries you intend to run.
Yet another alternative to using joins is to denormalize your data. Historically, denormalization was reserved for performance-sensitive code, or when data should be snapshotted (like in an audit log). However, with the ever- growing popularity of NoSQL, many of which don’t have joins, denormalization as part of normal modeling is becoming increasingly common. This doesn’t mean you should duplicate every piece of information in every document. However, rather than letting fear of duplicate data drive your design decisions, consider modeling your data based on what information belongs to what document.
So,
student
{
_id: ObjectId(...),
name: 'Jane',
courses: [
{
name: 'Biology 101',
mark: 85,
id:bio101
},
]
}
If its a RESTful API data, replace the course id with a GET link to the course resource
We can define the so-called foreign key
in MongoDB. However, we need to maintain the data integrity BY OURSELVES. For example,
student
{
_id: ObjectId(...),
name: 'Jane',
courses: ['bio101', 'bio102'] // <= ids of the courses
}
course
{
_id: 'bio101',
name: 'Biology 101',
description: 'Introduction to biology'
}
The courses
field contains _id
s of courses. It is easy to define a one-to-many relationship. However, if we want to retrieve the course names of student Jane
, we need to perform another operation to retrieve the course
document via _id
.
If the course bio101
is removed, we need to perform another operation to update the courses
field in the student
document.
More: MongoDB Schema Design
The document-typed nature of MongoDB supports flexible ways to define relationships. To define a one-to-many relationship:
Embedded document
- Suitable for one-to-few.
- Advantage: no need to perform additional queries to another document.
- Disadvantage: cannot manage the entity of embedded documents individually.
Example:
student
{
name: 'Kate Monster',
addresses : [
{ street: '123 Sesame St', city: 'Anytown', cc: 'USA' },
{ street: '123 Avenue Q', city: 'New York', cc: 'USA' }
]
}
Child referencing
Like the student
/course
example above.
Parent referencing
Suitable for one-to-squillions, such as log messages.
host
{
_id : ObjectID('AAAB'),
name : 'goofy.example.com',
ipaddr : '127.66.66.66'
}
logmsg
{
time : ISODate("2014-03-28T09:42:41.382Z"),
message : 'cpu is on fire!',
host: ObjectID('AAAB') // Reference to the Host document
}
Virtually, a host
is the parent of a logmsg
. Referencing to the host
id saves much space given that the log messages are squillions.
References:
- 6 Rules of Thumb for MongoDB Schema Design: Part 1
- 6 Rules of Thumb for MongoDB Schema Design: Part 2
- 6 Rules of Thumb for MongoDB Schema Design: Part 3
- Model One-to-Many Relationships with Document References
참고URL : https://stackoverflow.com/questions/6334048/foreign-keys-in-mongo
'program tip' 카테고리의 다른 글
React 입력 defaultValue가 상태로 업데이트되지 않습니다. (0) | 2020.10.08 |
---|---|
중복되지 않는 목록 구현이 있습니까? (0) | 2020.10.08 |
큰 단어 시퀀스에서 상위 K 개의 빈번한 단어를 찾는 가장 효율적인 방법 (0) | 2020.10.08 |
CanExecute가 처음 호출 될 때 WPF CommandParameter가 NULL입니다. (0) | 2020.10.08 |
목록의 요소 쌍 결합-Python (0) | 2020.10.08 |