Filtering elements in mongodb collection with ruby -


i want children names female in collection in mongodb using ruby:

the elements in collection this:

 [  { "name" => "john",    "children" => [{"genre" => "male", "name" => "rick"},                   {"genre" => "female", "name" => "mary"}                  ]  },  { "name" => "richard",    "children" => [{"genre" => "female", "name" => "vicky"},                   {"genre" => "female", "name" => "mary"}                  ]  }] 

when execute:

collection.find({"children" => {"genre" => "female"}}) 

i mongo::operationtimeout: timed out waiting on socket read.

moreover, don't want list of parents, list of different female children.

if use pure ruby, with:

collection.find({}).map { |d|     d["doc"]["children"].select { |rh|        rh["genre"] == "female"    }.map { |r|        r["name"]    } }.flatten.uniq 

but have millions of entries , takes lot of time. mongodb surely have way return result natively.

i cannot socket timeout got, query:

collection.find({"children" => {"genre" => "female"}}) 

does not give expect. checks exact equality between children field , given hash. correct way execute query is:

collection.find("children.genre" => "female") 

but still finds parents have @ least 1 female child. male children of these parents included in view , have filter them after getting result.

alternatively, can whole selection aggregate():

collection.aggregate([   {:$unwind => '$children'},   {:$match => {'children.genre' => 'female'}},   {:$group => {_id: '$children'}} ]).map { |c| c[:_id] } 

Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

Kivy: Swiping (Carousel & ScreenManager) -