在mongodb中建模关系

    科技2022-07-12  128

    MongoDB is a schema-less NoSQL database that operates with documents and collections. Unlike SQL databases, MongoDB can store documents in JSON format and its structure can vary, thus emphasizing on high scalability of the system and reduced complexity on deployment.

    MongoDB是一种无模式的NoSQL数据库,用于处理文档和集合。 与SQL数据库不同,MongoDB可以JSON格式存储文档,并且其结构可以变化,因此着重于系统的高可伸缩性和降低的部署复杂性。

    相关对象 (Relating Objects)

    In relational databases, relationships enforce data integrity. But in MongoDB and other NoSQL databases, there are no relationships between documents. Therefore, documents are independent. However, there are some approaches to model these relationships between documents.

    在关系数据库中,关系强制执行数据完整性。 但是在MongoDB和其他NoSQL数据库中,文档之间没有关系。 因此,文件是独立的。 但是,有一些方法可以为文档之间的这些关系建模。

    Scenario: I’ve been working on an e-wallet app recently, and here is a simple functionality to understand it better. This app allows users to store one or more bank cards in their e-wallet.

    场景: 我最近一直在开发电子钱包应用程序,这里有一个简单的功能可以更好地理解它。 此应用程序允许用户在其电子钱包中存储一张或多张银行卡。

    Based on the one-to-many relationship mentioned in this scenario, let’s explore the possible approaches to modeling relationships in MongoDB.

    基于此场景中提到的一对多关系,让我们探索在MongoDB中建模关系的可能方法。

    使用参考 (Using references)

    This method is called normalization. To implement this, we will have two separate collections for the user and bank card, as shown below:

    这种方法称为标准化 。 为此,我们将为用户卡和银行卡提供两个单独的集合,如下所示:

    let bankCard = { id:'', number:''}let user: { id:'', name:'', bankCard:'id'}

    In this example, in addition to the properties of the user object, the ID of the bankCard object is passed as a reference to the bankCard object in the user object.

    在此示例中,除了user对象的属性外, bankCard对象的ID还作为对user对象中bankCard对象的引用传递。

    However, these documents are independent, even though we are referring to the bank card document via the id property. There is no relationship between them.

    但是,即使我们通过id属性引用银行卡文档,这些文档也是独立的。 它们之间没有关系。

    As per the scenario, a user may have more than one bank card. Therefore, we replace the bankCard property in the user document with an array of IDs as follows: bankCards:[‘id1’, ‘id2’, ‘id3'].

    根据方案,用户可能拥有多个银行卡。 因此,我们将用户文档中的bankCard属性替换为以下ID数组: bankCards:['id1', 'id2', 'id3'] 。

    As this approach is similar to that of relational databases, data manipulation is concentrated at a single point, thus promoting consistency of data.

    由于此方法与关系数据库的方法相似,因此数据操作集中在单个点上,从而促进了数据的一致性。

    使用嵌入式文档 (Using embedded documents)

    This method is called denormalization. To implement this, we will have to embed the bank card object within the user object.

    此方法称为反规范化 。 为了实现这一点,我们将必须在user对象中嵌入银行卡对象。

    let user = { id:'', name:'',bankCard: { id: '', number:'', }}

    In this example, the user object has its own properties. In addition to that, it will contain the bankCard object and its respective properties.

    在此示例中, user对象具有其自己的属性。 除此之外,它将包含bankCard对象及其各自的属性。

    For situations where a user has more than one bank card, you can replace the bankCard object with an array of bank card objects: bankCards:[{id:’id1’, number:’’}, {id:’id2’, number:’’}].

    对于用户拥有多个银行卡的情况,您可以用一系列银行卡对象替换bankCard对象: bankCards:[{id:'id1', number:''}, {id:'id2', number:''}] 。

    By embedding one document within the other, we can improve the query performance of the system, thus saving time and improving speed.

    通过将一个文档嵌入另一个文档中,我们可以提高系统的查询性能,从而节省时间并提高速度。

    权衡 (The Trade-Off)

    If you are from an SQL background, you are most likely biased towards using references, whereas some might be comfortable with the embedding documents approach. But you can’t have both approaches at the same time.

    如果您来自SQL背景,则很可能会偏向于使用引用,而有些人可能更喜欢嵌入文档的方法。 但是您不能同时使用两种方法。

    Both approaches have their pros and cons. Therefore, you have a trade-off between consistency and query performance.

    两种方法各有利弊。 因此,您需要在一致性和查询性能之间进行权衡。

    一致性 (Consistency)

    When using references, documents are neat and less congested when in comparison to embedded documents. Therefore, we have two clean and independent documents.

    与嵌入文档相比,使用参考时,文档整齐且不拥挤。 因此,我们有两个干净且独立的文件。

    This approach is similar to that of relational databases. Therefore, suppose we want to update a specific document. We only have a single place to modify. Therefore, this approach is consistent.

    这种方法类似于关系数据库的方法。 因此,假设我们要更新特定的文档。 我们只有一个地方可以修改。 因此,这种方法是一致的。

    However, to load the data, we might have to run additional queries, thus reducing the querying performance. Sometimes, there are scenarios where you will have to run the query fast, and in such situations, proceeding with using references is not recommended.

    但是,要加载数据,我们可能必须运行其他查询,从而降低查询性能。 有时,在某些情况下,您将不得不快速运行查询,在这种情况下,建议不要继续使用引用。

    查询效果 (Query performance)

    When embedding documents, we have a single document with all the details of both documents. One of the strongest advantages of embedding documents is that you can load both the user details and the bank card details with a single query, thus improving speed and querying performance.

    嵌入文档时,我们只有一个文档,其中包含两个文档的所有详细信息。 嵌入文档的最大优势之一是,您可以通过单个查询同时加载用户详细信息和银行卡详细信息,从而提高了速度和查询性能。

    However, documents might look congested — especially if the documents have a lot of properties by themselves.

    但是,文档可能看起来很拥挤-特别是如果文档本身具有很多属性。

    Suppose an update or change to the subdocument is made. The risks are severe, as sometimes there are more documents to be updated. And if an update fails at any point, some parts will not be updated. Therefore, the data is inconsistent. This is one of the biggest drawbacks when applying this technique.

    假设对子文档进行了更新或更改。 风险很严重,因为有时会有更多文档需要更新。 并且,如果更新在任何时候失败,则某些部分将不会更新。 因此,数据不一致。 这是应用此技术时的最大缺点之一。

    混合方法 (The Hybrid Approach)

    Considering the issues addressed above, when developing complex applications, chances are that documents will have many properties (more than 50 each). In such situations, referencing or embedding wouldn’t suffice and would directly impact the system’s performance.

    考虑到上述问题,在开发复杂的应用程序时,文档很可能会具有许多属性(每个属性超过50个)。 在这种情况下,引用或嵌入是不够的,并且将直接影响系统的性能。

    概念 (Concept)

    In the hybrid approach, two documents (user and bank card) are created with each having its list of properties. Then, the necessary properties of the subdocument (bank card) are extracted and embedded within the user document:

    在混合方法中,将创建两个文档(用户和银行卡),每个文档都有其属性列表。 然后,提取子文档(银行卡)的必要属性并将其嵌入用户文档中:

    let bankCard = { id:'', name:'', number:'', expiry:''}let user = { id:'', name:'', dob:'', bankCard: { id: 'ref', number:'', }}

    In this approach, the bank card has a separate document and only the necessary properties of the bank card document are extracted and placed in the user document as an object amongst the other user properties. Therefore, this avoids the need to store all the properties of the bank card in the subdocument.

    在这种方法中,银行卡具有单独的文档,并且仅提取银行卡文档的必要属性,并将其放置在用户文档中作为其他user属性中的对象。 因此,这避免了将银行卡的所有属性存储在子文档中的需要。

    As the subdocument exclusively has the necessary properties, this approach influences an optimized querying performance and consistency throughout the system.

    由于子文档专门具有必要的属性,因此该方法会影响整个系统的优化查询性能和一致性。

    应用 (Application)

    When developing an e-commerce application, you will have the following documents in your database: products, orders, shopping carts, etc. When placing an order, you will require a snapshot of the product and certain details, such as product name and price at the given point in time.

    开发电子商务应用程序时,数据库中将包含以下文档:产品,订单,购物车等。下订单时,您将需要产品快照和某些详细信息,例如产品名称和价格在给定的时间点。

    In such a scenario where a snapshot of data is required, the hybrid approach is recommended.

    在需要数据快照的情况下,建议使用混合方法。

    结论 (Conclusion)

    Having discussed the pros and cons, the best approach is entirely your decision, considering the application and querying requirements. Therefore, you have to decide the queries beforehand and design the relationships based on the queries to make the trade-off. More information on modeling relationships can be found in MongoDB’s documentation.

    讨论了利弊之后,最好的方法完全是您的决定,同时考虑应用程序和查询要求。 因此,您必须事先决定查询并根据查询设计关系以进行权衡。 有关建模关系的更多信息,请参见MongoDB的文档 。

    I hope this article has educated you on how to model relationships in MongoDB. Have fun learning and coding!

    我希望本文能使您了解如何在MongoDB中建立关系模型。 祝您学习和编码愉快!

    翻译自: https://medium.com/better-programming/modeling-relationships-in-mongodb-b69b93181c48

    相关资源:微信小程序源码-合集6.rar
    Processed: 0.018, SQL: 8