ruby on rails - Mongoid access nested attributes with attributes.values_at? -


given following document (snippet):

{     udid: "0e321dd8-1983-4502-b214-97d6fb046746",        person: {         "firstname": "jacob",         "lastname": "prince"     } } 

i'n console can do:

mycollection.first.attributes.values_at("udid", "person") 

this returns person hash.

now want single field. these doesn't work (person.firstname):

mycollection.first.attributes.values_at("udid", "person.firstname") mycollection.first.attributes.values_at("udid", "person[:firstname]") mycollection.first.attributes.values_at("udid", "person['firstname']") 

how how access person child-document?

i'm in need have users select fieds want export. thinking along lines of doing this:

class foo     include mongoid::document       # fields definitions     embeds_one :person # 2 fields: firstname, lastname      def to_csv *columns        attributes.values_at *columns     end end 

whats (the most) efficient way select specific fields?

if know fields , nested keys, using ruby v2.3+ can utilise dig() built-in method. example:

document = collection.find({},{'projection' => {'uid' => 1, "person.firstname" => 1 }}).first result = [document.dig("uid"), document.dig("person", "firstname")] puts result.inspect 

alternatively, depending on application use case utilise mongodb aggregation pipeline, $project operator example:

document = collection.aggregate([{"$project"=>{ :uid=>"$uid", :person_firstname=>"$person.firstname"}}]).first puts document.values_at("uid", "person_firstname").inspect 

note projection above renames nested person.firstname flatten field called person_firstname.

see mongodb ruby driver: aggregation tutorial


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -