Search code examples
mongodbnestednested-documents

MongoDB querying nested documents


I have records like:

{
    "_id" : ObjectId("5f99cede36fd08653a3d4e92"),
    "accessions" : {
        "sample_accessions" : {
            "5f99ce9636fd08653a3d4e86" : {
                "biosampleAccession" : "SAMEA7494329",
                "sraAccession" : "ERS5250977",
                "submissionAccession" : "ERA3032827",
                "status" : "accepted"
            },
            "5f99ce9636fd08653a3d4e87" : {
                "biosampleAccession" : "SAMEA7494330",
                "sraAccession" : "ERS5250978",
                "submissionAccession" : "ERA3032827",
                "status" : "accepted"
            }
         }
     }
}

How do I query by the mongo id in sample_accessions? I thought this should work but it doesn't. What should I be doing?

db.getCollection('collection').find({"accessions.sample_accessions":"5f99ce9636fd08653a3d4e86"})

Solution

  • The id is a key and check whether key is exists or not use $exists, customize response using project to get specific object

    db.getCollection('collection').find(
      {
        "accessions.sample_accessions.5f99ce9636fd08653a3d4e86": {
          $exists: true
        }
      },
      { sample_doc: "$accessions.sample_accessions.5f99ce9636fd08653a3d4e86" }
    )
    

    Playground