MongoDB find()在匹配(字段,值)时返回子文档

时间:2015-04-05 04:51:19

标签: json mongodb find subdocument

这是一个包含2个json文件的集合。我正在搜索特定字段:对象中的值,并且在匹配的情况下必须返回整个子文档(来自集合的特定子文档必须从以下集合中的2个子文档中返回)。提前谢谢。

{
"clinical_study": {
"@rank": "379",
"#comment": [],
"required_header": {
  "download_date": "ClinicalTrials.gov processed this data on March 18, 2015",
  "link_text": "Link to the current ClinicalTrials.gov record.",
  "url": "http://clinicaltrials.gov/show/NCT00000738"
},
"id_info": {
  "org_study_id": "ACTG 162",
  "secondary_id": "11137",
  "nct_id": "NCT00000738"
},
"brief_title": "Randomized, Double-Blind, Placebo-Controlled Trial of Nimodipine for the Neurological Manifestations of HIV-1",
"official_title": "Randomized, Double-Blind, Placebo-Controlled Trial of Nimodipine for the Neurological Manifestations of HIV-1",
}

{
"clinical_study": {
"@rank": "381",
"#comment": [],
"required_header": {
  "download_date": "ClinicalTrials.gov processed this data on March 18, 2015",
  "link_text": "Link to the current ClinicalTrials.gov record.",
  "url": "http://clinicaltrials.gov/show/NCT00001292"
},
"id_info": {
  "org_study_id": "920106",
  "secondary_id": "92-C-0106",
  "nct_id": "NCT00001292"
},
"brief_title": "Study of Scaling Disorders and Other Inherited Skin Diseases",
"official_title": "Clinical and Genetic Studies of the Scaling Disorders and Other Selected Genodermatoses",
}

1 个答案:

答案 0 :(得分:0)

您的示例文档格式错误 - 现在两个clinical_study个键都是同一个对象的一部分,并且该对象缺少结束}。我假设您希望它们是两个单独的文档,尽管您将它们称为子文档。如果它们都在同一个键下命名,那么将它们作为文档的子文档是没有意义的。你无法以这种方式保存文档,并且在mongo shell中它会默默地用第二个替换第一个键实例:

> var x = { "a" : 1, "a" : 2 }
> x
{ "a" : 2 }

如果您只想在clinical_study上匹配时返回文档的clinical_study.@rank部分,请使用投影:

db.test.find({ "clinical_study.@rank" : "379" }, { "clinical_study" : 1, "_id" : 0 })

如果您认为clinical_study文档是较大文档中数组的元素,那么请使用$。这里,clinical_study现在是一个数组字段的名称,其中包含非文档中clinical_study键的两个值作为其元素:

db.test.find({ "clinical_study.@rank" : "379" }, { "_id" : 0, "clinical_study.$" : 1 })