2

I am using Mongoid. I have a document that looks like the following:

Pet:
  foo: {bar: 1, foobar: 2}
  another_attr: 1

In this case, preferably using Mongoid, how would I query for all pets that have a bar value greater than 0 where another_attr is equal to 1?

randombits
  • 47,058
  • 76
  • 251
  • 433

2 Answers2

7

In mongo shell:

db.pets.find({"foo.bar":{$gt:0}, another_attr:1});

In mongoid:

Pet.where(:'foo.bar'.gt => 0, :another_attr => 1)
Eve Freeman
  • 32,467
  • 4
  • 86
  • 101
0

To find all pets with a bar value greater than 0, you can use the $gt keyword in your query. To access a nested field (bar), you can use dot notation :

db.pet.find( {"foo.bar" : {$gt : 0}})

Then, to also require that another_attr is equal to 1, you can just add another requirement into the query:

db.pet.find( {"foo.bar" : {$gt : 0} , another_attr : 1 } )

You can find documentation about advanced queries here: http://www.mongodb.org/display/DOCS/Advanced+Queries

Louisa
  • 861
  • 6
  • 5