【问题标题】:Selecting multiple documents using a criteria in mongoid使用 mongoid 中的条件选择多个文档
【发布时间】:2025-12-26 21:30:06
【问题描述】:

我是 mongodb 和 mongoid 的新手。我习惯了 Ruby 中的 ActiveRecord/mysql 在 Rails 上,请原谅我的无知。

在 ActiveRecord 世界中,如果我想搜索满足某个特定条件的所有记录 标准(来自特定邮政编码的学生),我可以使用

students = Student.where(zipcode: "12345")

这将返回一个学生数组。

如果我查询,则使用 Mongoid

Student.all.where(zipcode: "12345") 

它只是返回一个条件,我必须使用像这样的迭代器

students = []
Student.all.where(zipcode: "12345").each  { |s|  students << s }

有没有更好的方法来做一个 Mongoid /Mongo 查询来获取所有文档 在不使用 ruby​​ 迭代器 (.each) 的情况下满足搜索条件?

我一直在参考来自的 mongoid 文档 https://docs.mongodb.org/ecosystem/tutorial/mongoid-queries/

并且找不到在一个查询中获取所有文档的示例。

【问题讨论】:

    标签: ruby-on-rails mongoid


    【解决方案1】:

    如果你这样想,你就是被控制台愚弄了:

    students = Student.where(zipcode: "12345")
    

    students 中为您提供Students 数组。这实际上在students 中为您提供了一个关系对象,但该关系的inspect(由控制台调用)将从您背后的数据库中加载记录;同样,一旦您尝试对关系执行任何数组操作,它就会从数据库中加载记录。

    Mongoid 的 where 行为相同,但它不需要在 ActiveRecord 关系将解决的所有相同情况下解析模型实例。

    如果您真的想要一个数组,最简单的方法(使用 ActiveRecord 和 Mongoid)是在关系/条件上调用 to_a

    # ActiveRecord
    students = Student.where(zipcode: "12345")      # students is a relation
    students = Student.where(zipcode: "12345").all  # students is still a relation
    students = Student.where(zipcode: "12345").to_a # students is now a real array
    
    # Mongoid
    students = Student.where(zipcode: "12345")      # students is a criteria
    students = Student.where(zipcode: "12345").all  # students is still a criteria
    students = Student.where(zipcode: "12345").to_a # students is now a real array
    

    在这两种情况下,如果您想要一个数组,那么只需使用to_a 这么说。

    【讨论】:

    • 非常感谢您的解释 - 现在说得通了。还刚刚了解到 Student.where(...) 返回一个条件,并且在将其分配给变量或迭代之前不会进行任何查询。