Januka samaranyake
Januka samaranyake

Reputation: 2597

Get Array element from JSON array from mongodb document

{
"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.

Upvotes: 3

Views: 520

Answers (1)

Vaibhav Patil
Vaibhav Patil

Reputation: 2983

Try this

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

Upvotes: 1

Related Questions