Retrieve only the needed element from an object array in MongoDB collection

Viewed 46

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": "nagendra@gmail.com"},{"_id":0, "skills":1})
{ "skills" : [ { "skillName" : "sql", "experienceInMonths" : 2 }, { "skillName" : "java", "experienceInMonths" : 3 } ] }

> db.userforms.find({"emailId":"nagendra@gmail.com"},{"_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"]}

1 Answers

Use aggregation:

db.userforms.aggregate([
  { $match: { emailId: "nagendra@gmail.com" } },
  { $project: { skillName: { $concatArrays: "$skills.skillName" } } }
])

will return:

{ "_id" : 0, "skillName" : [ "sql", "java" ] }

Related