3
{
"employees" : [ 
    {
        "name" : "XXX",
        "id" : "1",
        "Salary" : [ 
            {
                "Month" : "XXXX",
                "Amount" : "XXXX",
            }, 
            {
                "Month" : "XXXX",
                "Amount" : "XXXX",
            }, 
            {
                "Month" : "XXXX",
                "Amount" : "XXXX",
            }
        ]
    }, 
    {
        "name" : "YYY",
        "id" : "2",
        "Salary" : [ 
            {
                "Month" : "YYYY",
                "Amount" : "YYYY",
            }, 
            {
                "Month" : "YYYY",
                "Amount" : "YYYY",
            }, 
            {
                "Month" : "YYYY",
                "Amount" : "YYYY",
            }
        ]
    }
],
}

This is sample of json format in mongodb document. I want to get the result as a one particular element from employees Array that search by name I tried these methods

db.abc.find({"employees.name": "XXX"},{employees: {$elemMatch: {name: "XXX"}}});

and

db.abc.find({ employees: { $elemMatch: { name: "XXX"} } })

none of those won't work. those methods give whole document as a result. can anyone give me a solution on that.

1 Answer 1

1

Try this

db.abc.find({"employees.name": "XXX"},{"employees.$":1})
Sign up to request clarification or add additional context in comments.

4 Comments

Yh. That works. Can you help me to do this with indexing
Please elaborate what you want to do?
Serch this using indexing
You have to set indexing first db.abc.ensureIndex({"employees.name" : 1}).

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.