I am working with MongoDB for the first time. I want to retrieve a particular field from an object array in MongoDB collection. I need help how to do this?
In my database there is a structure called skills which is in the form of array. I want to retrieve both the skillName and experienceInMonths individually.
{
"skills" : [
{
"skillName" : "sql",
"experienceInMonths" : 2
},
{
"skillName" : "java",
"experienceInMonths" : 3
}
]
}
I tried to retrieve the particular field using $elemMatch.
But, I am not getting the expected result.
> db.userforms.find({"emailId": "[email protected]"},{"_id":0, "skills":1})
{ "skills" : [ { "skillName" : "sql", "experienceInMonths" : 2 }, { "skillName" : "java", "experienceInMonths" : 3 } ] }
> db.userforms.find({"emailId":"[email protected]"},{"_id":0, "skills":{$elemMatch: {"skillName":"sql"}}})
{ "skills" : [ { "skillName" : "sql", "experienceInMonths" : 2 } ] }
My actual result is: { "skills" : [ { "skillName" : "sql", "experienceInMonths" : 2 } ] }
But the required result is: {"skillName" : ["sql", "java"]}
{ $project: { skillName: "$skills.skillName" } }