【问题标题】:Mongoid and Mongodb queryingMongoid 和 Mongodb 查询
【发布时间】:2013-07-28 12:50:42
【问题描述】:

我有这样的数据结构

Courses
{
    "name" : "Course1",
    "student_id"
    "subjects" :
    [{
      "level" : "1",
      "short_name" : "Maths",
      "topics" : [{
              "name" : "Algebra 101",
              "week" : "1",
              "submission_week" : ISODate("2013-07-28T00:00:00Z"),
              "correction_week" : ISODate("2013-07-28T00:00:00Z")
              },
              {
              "name" : "Algebra 201",
              "week" : "1",
              "submission_week" : ISODate("2013-07-28T00:00:00Z"),
              "correction_week" : ISODate("2013-07-28T00:00:00Z")
              }
     ]},
     {
      "level" : "2",
      "short_name" : "Chem"
     }
    ]
}

我正在尝试使用 Mongoid 检索所有主题。

我尝试了各种查询,但似乎无法得到它。

例如,我不明白为什么这不起作用?

Topic.where( name: "Algebra 101", 'subject.short_name' =>"Maths", 'subject.course.name' =>"Course1")

我可以这样查询吗?

我的红宝石代码是

class Course
  embeds_many :subjects

class Subject
  embedded_in :course
  embeds_many :topics

class Topic
  embedded_in :subject

【问题讨论】:

    标签: ruby-on-rails mongodb mongoid


    【解决方案1】:

    据我所知,只能在最顶层的模型上进行这样的查询(在本例中为 Course);我还没有看到直接获得这样的嵌入式模型的方法。

    所以这应该可以,但只会给你Course

    Course.where(name: 'Course1', 'subjects.short_name' => 'Maths', 'subjects.topics.name' => "Algebra 101")
    

    这是(不幸的是相当丑陋的)查询应该给你你想要的:

    Course.where(name: 'Course1').subjects.where(short_name: 'Maths').topics.where(name: 'Algebra 101')
    

    【讨论】:

      猜你喜欢
      • 2011-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多