2017-08-14 5 views
0

:私のコンソールI'nMongoidはattributes.values_atを持つネストされた属性にアクセスしますか?次のドキュメント(スニペット)が与えられ

{ 
    udid: "0E321DD8-1983-4502-B214-97D6FB046746", 
    person: { 
     "firstname": "Jacob", 
     "lastname": "Prince" 
    } 
} 

は、私は基本的に行うことができます。

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

これはハッシュとしてを返します。

ここでは1つのフィールドが必要です。しかし、これらは機能しません。(person.firstname):

どのように人の子文書にアクセスしますか?

私は、ユーザを持っている必要がありますは、どのfieds彼らがエクスポートしたいかを選択します。

class Foo 
    include Mongoid::Document 

    # fields definitions 
    embeds_one :person # two fields: firstname, lastname 

    def to_csv *columns 
     attributes.values_at *columns 
    end 
end 

答えて

0

いただきまし特定のフィールドを選択する(最も)効率的な方法:私はこのような何かをやっての線に沿って考えていましたか?

すでにフィールドとそのネストされたキーが分かっている場合は、Ruby v2.3 +を使用してdig()ビルトインメソッドを利用できます。また

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

、アプリケーションのユースケースに応じて、あなたはまた、例えばMongoDB Aggregation Pipeline、特に$project operator を利用することができる:例えば上記の投影がフラット化フィールドにネストされたperson.firstnameの名前を変更すること

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

注意をperson_firstnameと呼ばれます。

も参照してください。MongoDB Ruby Driver: Aggregation Tutorial

関連する問題