【问题标题】:MongoDB find() to return the sub document when a (field,value) is matchedMongoDB find() 在匹配(字段,值)时返回子文档
【发布时间】:2015-06-09 20:15:35
【问题描述】:

这是一个包含 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",
}

【问题讨论】:

  • 您有哪个特定字段/值和哪个子文档的示例吗?
  • 我用这个模式搜索过 ("clinical_study.@rank", "379");并且它被匹配但无法取回它所在的子文档。
  • 在 mongo shell db.TargetCollection.find({"clinical_study.@rank": "379"}) 中执行此查询会得到什么结果
  • 我得到了我搜索的相同值而不是子文档

标签: json mongodb find subdocument


【解决方案1】:

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

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

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

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 })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 2015-10-31
    • 2021-08-06
    • 2018-06-13
    • 2014-08-02
    • 2016-09-27
    • 2019-09-18
    相关资源
    最近更新 更多