[英]With MongoMapper, how can I find records where an ID doesn't exist in another table?
I have two models, User and Class. 我有两个模型,User和Class。 In MySQL, I could find users not in a class with something like:
在MySQL中,我可以找到不在类中的用户,例如:
SELECT * FROM Users WHERE id NOT IN (SELECT user_id FROM Classes)
How can I do something similar with MongoMapper? 如何使用MongoMapper做类似的事情? I've been able to in the Mongo console with:
我已经能够在Mongo控制台中执行以下操作:
db.users.find({user_id:{$ne:db.classes.find({}, {user_id:1})}});
but I can't figure out the syntax using MongoMapper. 但是我无法使用MongoMapper确定语法。
The Mongo snippet you posted is two queries. 您发布的Mongo片段是两个查询。 The MongoMapper equivalent is:
MongoMapper等效项是:
classy_users_ids = MyClass.fields(:user_id).find_each.map(&:user_id).uniq
classless_users = User.where(:id.nin => classy_users_ids)
If you have a lot of users, the first query might be more efficient if you skip the conversion to MongoMapper::Document
's with the following: 如果您有很多用户,则使用以下命令跳过对
MongoMapper::Document
的转换,则第一个查询可能会更高效:
classy_users_ids = MyClass.collection.distinct(:user_id)
如果它们的关系类似于Class ... has_many :users
,则可以直接与user_ids
进行匹配:
Class.where(:user_ids.ne => user.id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.