mongodb: use nested document or separate collectio

2019-07-25 03:11发布

问题:

I'm just starting with mongoDB.

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?

回答1:

It all depends on the use case - like nature of data, frequency of read, data access patters, etc.

In your case, it looks like the "small data record" is dependent on the user data and not really a standalone data. Since the size is also small, it's better to embed the data in user collection.



回答2:

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

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

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)

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 nosql