MongoDB 只提供“文档”,而不是任意的单个字段值或字段值数组。
因此,您将始终必须按键从文档中提取单个值。
然而,MongoDB 和文档的主要优势在于与编程语言结构相匹配,
因此使您能够使用您的编程语言。
您应该将您的编程语言视为您选择的主要工具。
MongoDB 查找查询仅允许简单的投影/选择顶级字段。
你可以使用聚合框架做更复杂的提取和转换,
但我建议您先使用您的编程语言。
我希望下面的测试能够为您说明这一切。
test.rb
require 'mongo'
require 'json'
require 'test/unit'
class MyTest < Test::Unit::TestCase
def setup
@coll = Mongo::MongoClient.new['test']['Gene']
doc = JSON.parse <<-EOT
{ "ADR" : [{"adverse_type" : "YYY"}],
"DrugDBI" : [{"cancer_type" : "XXX", "drug_name" : "AAAA"}, {"cancer_type" : "1405-87-4", "drug_name" : "LLL"}],
"_id" : "A2M",
"ts" : {"$date" : 1395239463625}
}
EOT
@coll.remove
@coll.insert(doc)
end
test "extract cancer drugs" do
@gene_v = "A2M"
doc = @coll.find({_id:@gene_v},fields:["DrugDBI"]).to_a.first
@gened = doc["DrugDBI"].collect{|cancer_drug| cancer_drug["drug_name"]}
assert_equal(["AAAA", "LLL"], @gened)
puts "Drugs related to genes -> <#{@gened}>"
doc = @coll.aggregate([
{"$match" => {"_id" => @gene_v}},
{"$unwind" => "$DrugDBI"},
{"$project" => {"drug_name" => "$DrugDBI.drug_name"}},
{"$group" => {"_id" => "$_id", "drug_name" => {"$push" => "$drug_name"}}}
]).to_a.first
@gened = doc["drug_name"]
assert_equal(["AAAA", "LLL"], @gened)
puts "Drugs related to genes -> <#{@gened}>"
end
end
$ ruby test.rb
Loaded suite test
Started
Drugs related to genes -> <["AAAA", "LLL"]>
Drugs related to genes -> <["AAAA", "LLL"]>
.
Finished in 0.010455 seconds.
1 tests, 2 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications