Rails + MongoDB - 查询Mongoid多值哈希字段

时间:2013-07-29 12:20:55

标签: ruby-on-rails mongodb mongoid

我正在使用Rails 3.2.8,Mongoid 3.1.4和Ruby 1.9.3

我有简单的JSON:

{
    _id: ObjectId("51f65be999c655122d0097ed"),
    association_chain: [
        {
            name: "VendorForecast",
            id: ObjectId("51f65be999c655122d0097ec")
        }
    ],
    scope: "vendor_forecast",
    original: {},
    modified: {
        category_id: ObjectId("51f65b3799c655122d00008e"),
        scenario_id: ObjectId("51f65b3799c655122d00002e"),
        period_id: ObjectId("51bf800b99c655fe13000152"),
        value: 150000,
        company_id: ObjectId("51f65b3699c655122d000002")
    },
    version: 1,
    action: "create",
    modifier_id: ObjectId("51f65b3799c655122d000006"),
    updated_at: ISODate("2013-07-29T12:11:21+00:00"),
    created_at: ISODate("2013-07-29T12:11:21+00:00")
}

我想获得所有具有

的模型
modified: {
  company_id: ObjectId("51f65b3699c655122d000002")
}

如果我只是简单地查询:

1.9.3p429 :026 > HistoryTracker.where(modified: {"company_id" => "51f654a099c655032a000002"}).size
 => 0 

我没有结果。

有没有想过如何让这个工作?

1 个答案:

答案 0 :(得分:2)

尝试:

HistoryTracker.where("modified.company_id" => Moped::BSON::ObjectId("51f654a099c655032a000002")}).count