简体   繁体   English

根据父级属性查询Mongodb集合

[英]Querying Mongodb collection based on parent's attribute

I've got a Posts document that belong to Users, and Users have an :approved attribute. 我有一个属于Users的Posts文档,并且Users具有:approved属性。 How can I query my Posts using Mongodb st I only get those for where User has :approved => true ? 我如何使用Mongodb查询我的帖子,我只能获取用户具有:approved => true帖子?

I could write a loop that creates a new array, but that seems inefficient. 我可以编写一个创建新数组的循环,但这似乎效率很低。

MongoDB does not have any notion of joins. MongoDB没有任何联接的概念。

You've stated in the comments that Posts and Users are separate collections, but your query clearly involves data from both collections, which would imply a join. 您已经在评论中指出“ Posts和“ Users是单独的集合,但是您的查询显然涉及两个集合中的数据,这意味着存在联接。

I could write a loop that creates a new array, but that seems inefficient. 我可以编写一个创建新数组的循环,但这似乎效率很低。

A join operation in SQL is basically a loop that happens on the server. SQL中的联接操作基本上是在服务器上发生的循环。 With no join support on the server side, you'll have to make your own. 在服务器端没有连接支持的情况下,您必须自己创建。

Note that many of the libraries (like Morphia) actually have some of this functionality built-in. 请注意,许多库(例如Morphia)实际上都内置了某些此功能。 You are using Mongoid which may have some of this support, but you'll have to do some hunting. 您正在使用Mongoid,它可能有部分支持,但是您必须做一些狩猎。

The easiest way to think about it would be to query for unique user ids of users who are approved and then query for post documents where the poster's user_id is in that set. 最简单的考虑方法是查询已批准用户的唯一用户ID,然后查询张贴者的user_id在该集合中的过帐文档。

As Rubish said, you could de-normalize by adding an approved field to the post document. 正如Rubish所说的,您可以通过在邮政单据中添加批准的字段来规范化。 When a user's approval status is toggled (they become approved or unapproved) do an update on the posts collection where, for all of that user's posts, you toggle the denormalized approval field. 切换用户的批准状态(他们变为批准或未批准)时,请对帖子集合进行更新,在该集合中,对于该用户的所有帖子,您都可以切换非规范化的批准字段。

Using the denormalized method lets you do one query instead of two (simplifying the logic for the most common case) and isn't too much of a pain to maintain. 使用非规范化方法,您可以执行一个查询而不是两个查询(简化了最常见情况的逻辑),并且维护起来不会太麻烦。

Let me know if that makes sense. 让我知道这是否有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM