2017-08-14 77 views
0

鉴于以下文件(片段):Mongoid访问具有attributes.values_at的嵌套属性?

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

I'n我的控制台我可以基本上做到:

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

这将返回哈希

现在我想单个字段。但这些不工作(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']") 

如何如何访问的人儿文档?

我需要有用户选择他们想要导出哪些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 例如:

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

注意,上面的投影重命名嵌套person.firstname成扁平化领域称为person_firstname

另请参见MongoDB Ruby Driver: Aggregation Tutorial