本文介绍了mongodb:使用嵌套文档或带有引用的单独集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用 mongoDB.

I'm just starting with mongoDB.

我必须存储用户数据.对于每个用户,每天都会添加一个小数据记录(不超过 500 字节)或更新其中的一些(大多数时间不超过 10 个).

I have to store user data. For each user there will be added a small data record (not more than 500 Bytes) each day or updated some (most of the time not more then 10) of them.

现在我的问题是,我应该将其建模为将数据记录嵌入在每个用户文档中的用户集合,还是应该将用户集合和数据记录集合与每个数据文档到用户文档的引用一起建模?

Now my question is, should I model this as a Collection of users with the data records embedded in each user document, or having a user collection and a data record collection with a reference from each data document to the user document?

推荐答案

这主要取决于您要在 DB 上执行的查询

It mostly depends on the queries you're going to do on the DB

我假设在您的数据库中您需要存储特定于用户的数据(姓名、地址、ecc)和其他"数据(您的小数据记录")

I assume that in your db you need to store user specific data (name, address, ecc.) and 'other' data ( your 'small data record' )

如果查询要获取用户特定数据以及其他"数据,您最好只使用用户集合并将其他"数据嵌入用户集合中.通过这种方式,您可以在一个查询中获取特定于用户的数据和其他"数据

If the queries are going to get user specific data along with 'other' data, you'd better to use only a user collection and embed the 'other' data in the user collection. This way you can get user specific data and 'other' data in one single query

如果查询将仅获取其他"数据(从 user_id 示例开始),并且您计划永远不需要用户特定数据以及其他"数据,则可以使用数据集合,其中您将存储您的其他"数据以及 user_id(例如更新数据)

If the queries are going to get only 'other' data (starting from example from a user_id ), and you plan to never need user specific data along with 'other' data, you could use a data collection, in which you'll store your 'other' data, along with the user_id (to update the data, for example)

请记住,通常不建议在 mongodb 中使用引用,除非您有充分的理由这样做,所以我会选择第一个解决方案

Keep in mind that usually, using references in mongodb is not recommended, unless you have a very good reason to do it, so i'd go for the first solution

这篇关于mongodb:使用嵌套文档或带有引用的单独集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 14:16