2

有没有办法通过代码对 Spring 说我在 MongoDB 中有一个表/集合,例如 Person。你怎么说它与另一个表有一对多的关系。这在 MongoDB 中是否可以通过 Spring 实现?

4

2 回答 2

3

It is possible for MongoDB to have 'relationships' with other databases and collections, these are called Manual References and DBRefs. Look in the documentation for database references. You should however be wary using these, as they will almost always perform poorly in comparison to using a single collection. Either your application or the driver is going to need to query twice for the data - once in the original collection and once in the other collection to resolve the reference.

It is a common mistake for those coming from a relational model to try and emulate joins in MongoDB with the use of DBRefs. In the example you give, a one-to-many relationship is likely better modelled in a single collection with embedding, like the following:

{
    "_id" : ObjectId(),
    "Name" : "Bob",
    "Cars" : {
        "CarName1" : "FirstCar",
        "CarName2" : "SecondCar"
    }
}

You can check out the docs on Schema Design for more information

于 2012-08-05T22:54:53.043 回答
2

MongoDb 不对多个集合之间的关系提供任何支持。它与数据库的sql方法不同。No-sql 支持由模式设计本身维护的逻辑关系。它的基本目标是减少对部分文档的依赖并加快流程。对于演示示例,您可以访问mongodb-useful-basics

于 2015-08-06T17:15:40.377 回答