Search code examples
jsonmongodbfindsubdocument

MongoDB find() to return the sub document when a (field,value) is matched


This is a single collection which has 2 json files. I am searching for a particular field: value in an object and the entire sub document must be returned in case of a match ( That particular sub document from the collection must be returned out of the 2 sub documents in the following collection). Thanks in advance.

{
"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",
}

Solution

  • Your example documents are malformed - right now both clinical_study keys are part of the same object, and that object is missing a closing }. I assume you want them to be two separate documents, although you call them subdocuments. It doesn't make sense to have them be subdocuments of a document if they are both named under the same key. You cannot save the document that way, and in the mongo shell it will silently replace the first instance of the key with the second:

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

    If you just want to return the clinical_study part of the document when you match on clinical_study.@rank, use projection:

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

    If instead you meant for the clinical_study documents to be elements of an array inside a larger document, then use $. Here, clinical_study is now the name of an array field which has as its elements the two values of the clinical_study key in your non-documents:

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