MongoDB nested objects

Viewed 34

I need help. Recently started teaching mongodb. I can't figure out how to access the nested items. Please help: how can I find the key to "profession"?

{
"_id" : ObjectId("60a4bbd1753b2bb53e6f7dba"),
"name" : "Bob",
"class" : 7.0,
"lessons" : [ 
    "english", 
    "mathematics"
],
"avgScore" : 3.5,
"parents" : [ 
    {
        "gender" : "female",
        "name" : "Ira"
    }, 
    {
        "gender" : "male",
        "name" : "Dima",
        "profession" : "programmer"
    }
]
}
2 Answers

There are multiple wasy you can do. You can use find() or aggregation(). Here I show you with find()

db.collection.find({
  parents: {
    $elemMatch: {
      profession: "programmer"
    }
  }
},
{
  "parents.profession.$": 1
})

Working Mongo playground

Related