Januka samaranyake Januka samaranyake - 2 months ago 6
JSON Question

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.

Answer

Try this

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