如何搜索MongoDB子文档部分匹配?

时间:2015-02-18 11:00:57

标签: ruby mongodb mongodb-query subdocument

我在MongoDB数据库中有一组描述会议地点的文档。它还包含有关会场开放时间的信息。

示例:

{
  _id: ObjectId("54ccbb90cbcb91146d000001"),
  name: "temp_can_add_slots_to_position",
  seats: 4,
  slots: [
    {
      _id: ObjectId("54ccbb91cbcb91146d000002"),
      start_time: 1441094400,
      end_time: 1441096200,
      status: "test"
    },
    {
      _id: ObjectId("54ccbb91cbcb91146d000003"),
      start_time: 1441096200,
      end_time: 1441098000,
      status: "open"
    },
    {
      _id: ObjectId("54ccbb91cbcb91146d000004"),
      start_time: 1441098000,
      end_time: 1441099800,
      status: "open"
    },
    {
      _id: ObjectId("54ccbb91cbcb91146d000005"),
      start_time: 1441099800,
      end_time: 1441101600,
      status: "open"
    },
    {
      _id: ObjectId("54ccbb91cbcb91146d000006"),
      start_time: 1441101600,
      end_time: 1441103400,
      status: "open"
    },
    {
      _id: ObjectId("54ccbb91cbcb91146d000007"),
      start_time: 1441103400,
      end_time: 1441105200,
      status: "open"
    },
    {
      _id: ObjectId("54ccbb91cbcb91146d000008"),
      start_time: 1441105200,
      end_time: 1441107000,
      status: "open"
    },
  ],
  type: "private"
}

我想搜索文档,只返回文档,并且子文档的状态为' open'。我似乎无法写一个'发现'可以实现这一目标的条款。

例如,我喜欢上面的文档,除了'插槽'对象ID为54ccbb91cbcb91146d000002的子文档。

例如,这会返回整个文档:

find({_id: ObjectId("54ccbb90cbcb91146d000001"),"slots.status": "open"}).limit(10)

(实际上坐在一些看起来像这样的Ruby里面):

def list_open_slots_at_a_position(id)
    working_position = @coll.find( { "_id:" => "ObjectId(\"#{id}\")", "slots.status:" => "open" } ).to_a
    puts working_position
end

我做错了什么?

0 个答案:

没有答案