简体   繁体   English

使用MongoMapper,如何查找另一个表中不存在ID的记录?

[英]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.

相关问题 如何找到一个ID在一个数组中或另一个ID在另一个数组中的所有记录? - How can I find all records where an id is in one array, or another id is in another array? 如何使用MongoMapper随机获取文档? - How can I fetch documents in a random order using MongoMapper? 如何使用MongoMapper扩展对象的默认构造函数? - How can I extend the default constructor for an object using MongoMapper? 如果属性不存在获取所有记录 - If property doesn't exist get all records 如何找到 $type 字段不等于“日期”的所有记录? - How can I find all records where $type of field not equal 'date'? MongoMapper无法通过简单的示例保存文档 - MongoMapper can't save a document with simple example MongoDB,如何更新一组嵌入式文档,或者如果不存在,请插入一个文档? - MongoDB, How can I update an embedded doc in a set or insert one if it doesn't exist? 如何查询 2 个集合以查找 _id 相同但 x 在 MongoDB 中不同的位置 - How can I query 2 collections to find where the _id is the same but x is different in MongoDB 我在哪里可以找到_id。$ oid的mongodb文档? - where can I find mongodb documentation for _id.$oid? 如果文档的 _id 已经存在,如何将数组元素推送到数组,如果 _id 不存在,如何创建新文档? - How to push array elements to an array if _id of documents already exists and create new document if _id doesn't exist?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM