gpt4 book ai didi

node.js - MongoDB 外键查询

转载 作者:可可西里 更新时间:2023-11-01 09:37:17 27 4
gpt4 key购买 nike

我有两个集合:

用户:

  • { id:"aaaaaa"年龄:19 性别:"f"}
  • { id:"bbbbbb"年龄:30, 性别:"m"}

评论:

  • { id:777777 , user_id:"aaaaaa", text:"一些评论数据"}
  • { id:888888 , user_id:"aaaaaa", text:"一些评论数据"}
  • { id:999999 , user_id:"bbbbbb", text:"一些评论数据"}

我想找到 sex=fage>18 的所有评论

(我不想嵌套,因为评论集合会很大)

最佳答案

您应该在每条评论中包含用户的数据(也称为非规范化):

{ id:777777 , user: { id:"aaaaaa", age:19 , sex:"f" } , text:"some review data" }
{ id:888888 , user: { id:"aaaaaa", age:19 , sex:"f" } , text:"some other review data" }
{ id:999999 , user: { id:"bbbbbb", age:20 , sex:"m" } , text:"mome review data" }

在这里,阅读这个link on MongoDB Data Modeling :

A Note on Denormalization

Relational purists may be feeling uneasy already, as if we were violating some universal law. But let's bear in mind that MongoDB collections are not equivalent to relational tables; each serves a unique design objective. A normalized table provides an atomic, isolated chunk of data. A document, however, more closely represents an object as a whole. In the case of a social news site, it can be argued that a username is intrinsic to the story being posted.

What about updates to the username? It's true that such updates will be expensive; happily, in this case, they'll be rare. The read savings achieved in denormalizing will surely outweigh the costs of the occasional update. Alas, this is not hard and fast rule: ultimately, developers must evaluate their applications for the appropriate level of normalization.

关于node.js - MongoDB 外键查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13111367/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com