您将如何在MongoDB中对此进行建模?

您将如何在MongoDB中对此进行建模?,mongodb,database-design,database-schema,nosql,Mongodb,Database Design,Database Schema,Nosql,有些产品有名称和价格 用户记录他们购买的产品 # option 1: embed logs product = { id, name, price } user = { id, name, logs : [{ product_id_1, quantity, datetime, comment }, { product_id_2, quantity, datetime, comment },

有些产品有名称和价格

用户记录他们购买的产品

# option 1: embed logs
product = { id, name, price }
user = { id, 
         name,
         logs : [{ product_id_1, quantity, datetime, comment },
                 { product_id_2, quantity, datetime, comment },
                 ... ,
                 { product_id_n, quantity, datetime, comment }] 
}
我喜欢这个。但如果产品ID的长度为12字节,数量和日期时间为32位(4字节)整数,注释平均为100字节,则一个日志的大小为12+4+4+100=120字节。文档的最大大小为4MB,因此每个用户的最大日志量为4MB/120bytes=33333。如果假设一个用户每天记录10次购买,那么在33333/10=3333天~9年的时间内达到4MB的限制。好吧,9年也许可以,但如果我们需要存储更多的数据呢?如果用户每天记录100次购买怎么办

这里的另一个选择是什么?我必须完全正常化吗

# option 2: normalized
product = { id, name, price }
log = { id, user_id, product_id, quantity, datetime, comment }
user = { id, name }

嗯。我们回到了关系模式。

是的,选项2是您的最佳选择。是的,您回到了关系模型,但是,您的数据最好以这种方式建模。我看不出选项2有什么特别的缺点,是您的数据要求您这样做,这不是一个糟糕的设计过程。

如果尺寸是主要问题,您可以使用mongo继续使用选项2

并使用Dbref将这些日志嵌入到用户中,类似于

       var log = {product_id: "xxx", quantity:"2", comment:"something"}
       db.logs.save(log)
       var user= { id:"xx" name : 'Joe', logs : [ new DBRef('logs ', log._id) ] }
       db.users.save(user)

为什么产品ID需要12个字节?也许您可以使用32位(或更少)序列?您还可以将注释移动到单独的集合,并按id引用注释。哦,很好。。那么通过自动递增手动生成ID?你会将最后分配的id值存储在哪里?@Diederik,将评论移出将是一件大事!但我想需要做两次查询才能得到日志和它们的评论。
       var log = {product_id: "xxx", quantity:"2", comment:"something"}
       db.logs.save(log)
       var user= { id:"xx" name : 'Joe', logs : [ new DBRef('logs ', log._id) ] }
       db.users.save(user)