How to print only the value within the child embedded document in MongoDB?

Viewed 55

I have the following data, this is one of the documents:

{
"_id": {
    "$oid": "607c6b658fedaf104caa78e9"
},
"awardYear": "1901",
"category": {
    "en": "Chemistry",
    "no": "Kjemi",
    "se": "Kemi"
},
"categoryFullName": {
    "en": "The Nobel Prize in Chemistry",
    "no": "Nobelprisen i kjemi",
    "se": "Nobelpriset i kemi"
},
"prizeAmount": 150782,
"prizeAmountAdjusted": 8567159,
"links": {
    "rel": "nobelPrize",
    "href": "http://masterdataapi.nobelprize.org/2/nobelPrize/che/1901",
    "action": "Get",
    "types": "application/json"
},
"laureates": [{
    "id": "160",
    "knownName": {
        "en": "Jacobus H. van 't Hoff"
    },
    "portion": "1",
    "sortOrder": "1"
}]}

I'm trying to retrive the names using dot notation with the code below on MongoDB Shell:

db.nobel.find({ "awardYear": '1901' },{
_id : 0,
"laureates.knownName.en": 1
})

My result is:

{ "laureates" : [ { "knownName" : { "en" : "Jacobus H. van 't Hoff" } } ] }

I want to have just the name (without the parents):

"Jacobus H. van 't Hoff"

I have also tried to exclude the "laureates" using ("laureates" = 0) but I received a path collision error, it would be great if you can help me. I'm using MongoDB Community Server 4.4.5. Thank you all in advance.

1 Answers

Demo - https://mongoplayground.net/p/5JYm2r_rtit

Use $first

db.collection.find(
 { "awardYear": "1901" },
 { _id: 0,"laureates": { $first: "$laureates.knownName.en" } }
)

Or You can use $arrayElemAt as mentioned in the comment by @turivishal

Demo - https://mongoplayground.net/p/0GoAN8g8dP_

db.collection.find(
 { "awardYear": "1901" },
 { _id: 0, "laureates": { $arrayElemAt: ["$laureates.knownName.en", 0] } }
)

Output

[
  {
    "laureates": "Jacobus H. van 't Hoff"
  }
]
Related