After reading MongoDB update data in nested field I set a nested element using
db.users.update ({_id: '123'}, { '$set': {"friends.0.emails.0.email" : '2222'} });
How do I access that element? (just the sub element not the whole document)
e.g. db.users.findOne({_id: '123'}, {'$elem':"friends.0.emails.0.email"});
For example:
If it were a JavaScript object it'd be
db.users["123"].friends[0].emails[0].email
If it were a Python dict it'd be
db.users["123"]["friends"][0]["emails"][0]["email"]
If it were a Ruby Hash it'd also be
db.users["123"]["friends"][0]["emails"][0]["email"]
Ideally the answer would be a function that accepts a list of keys (e.g. [ "friend", 0, "emails", 0 , "email" ]
) and returns the value of that nested element (e.g. 2222
).
I'm a Computer Science student and I work as a full stack dev: none of my peers, professors, co-workers or bosses can answer this question. I'm trying to learn mongo and accessing an element is one of the first things I thought to learn. I've spent days reading related stack overflow questions and Mongo documentation about $filter, $elem, the dot operator, and the $ operator, but nothing seems to explain how to simply access a nested element.
Here are some of the related questions I found that are not what I'm looking for
MongoDB - how to query for a nested item inside a collection?
^Talks about a range of elements (I only want 1)
MongoDB nested array query
^Checking membership of arrays-of-arrays (I just want to access an elem not check membership)
Get particular element from mongoDB array
^Filters using a query (color='Red') but I don't want to filter by a query, I want to retrieve an exact-unique index (e.g the 0th email)
retrieve a nested document with mgo
^this is kind of close, but the user never posted the mongo answer and instead referenced a go-Lang post. It also doesn't cover the possibility of arrays.