2

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"]}

1
  • 1
    try this { $project: { skillName: "$skills.skillName" } } Commented Jan 9, 2019 at 17:22

1 Answer 1

2

Use aggregation:

db.userforms.aggregate([
  { $match: { emailId: "[email protected]" } },
  { $project: { skillName: { $concatArrays: "$skills.skillName" } } }
])

will return:

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

Sign up to request clarification or add additional context in comments.

3 Comments

Dolly wants "skillname", not "skills" ;)
'skillName' will be. I misspelled the return. (edited)
Are you querying userforms? I wrote db.users the first time but then I edited. It should work, I've checked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.