Donald
Donald

Reputation: 233

Rails 3 + MongoDB: How to do a nested query?

I am using Ruby Mongo Driver.

  @surname = coll2.find("name" => {"surname" => "testing"})

Shouldn't this be working? I get no results.

I have {"name" : { "surname" : "testing" }}

Upvotes: 1

Views: 1076

Answers (3)

Vadim
Vadim

Reputation: 633

For me, it worked only with curly brackets. Like that:

col2.find({"name.surname": "testing"})

Upvotes: 0

Evangelos
Evangelos

Reputation: 11

I think that the following would work too

coll2.find("name.surname"=>"testing").first

Upvotes: 1

Dylan Markow
Dylan Markow

Reputation: 124419

Your code should work perfectly.

> coll2.insert({"name" => {"surname" => "testing"})
# => BSON::ObjectId('4dcb2e53abad691f62000002')
> coll2.insert({"name" => {"surname" => "another"})
# => BSON::ObjectId('4dcb2e53abad691f62000003')
> coll2.find().count
# => 2
> coll2.find("name" => {"surname" => "testing"}).count
# => 1
> coll2.find("name" => {"surname" => "testing"}).first
# => {"_id"=>BSON::ObjectId('4dcb2e53abad691f62000002'), "name"=>{"surname"=>"testing"}} 

Upvotes: 0

Related Questions