I've got the following MongoDB/Mongoid document:
#<Event
_id: 51e406a91d41c89fa2000002,
namespace: :namespace,
bucket: "order_created",
data: {
"order"=>{
"id"=>100,
"deleted_at"=>nil,
"created_at"=>2011-10-06 15:45:04 UTC,
"updated_at"=>2013-07-10 16:37:07 UTC,
"completed_at"=>2013-07-10 16:37:07 UTC
}
}>
Here is the event class definition:
class Event
include Mongoid::Document
field :namespace, type: Symbol
field :bucket, type: String
field :data, type: Hash
end
I want to find and update it using the find_and_modify method in Mongoid but I can't figure out how to properly structure the search criteria to search the data field properly.
Specifically, I want to find data.order.id = 100
. I've tried the following with no luck:
Event.where(:data.order.id => 100)
Event.where(:'data["order"]["id"]' => 100)
Event.where( { data: { order: { id: 100 } } } )
Event.where( { data: { :"order" => { :"id" => 100 } } }
The latter returns nil, but the former (and, from the documentation I've read, the correct way to do it) gives me a SyntaxError: unexpected ':'
.
This is with Mongoid 3.1.4 and MongoDB 2.4.5.
Answering my own question. The Event class is not referencing a collection, which is what's critical for the Criteria search to work. I've instantiated a new db object to use against the collection and the find/where methods work. Here's an example:
@db = Mongoid::Sessions.default
@db[:events].find().first['order']
@db[:events].where("data.order.id" => 100).first