I have a collection with documents like the following:
{
name: "Johann",
surname: "Esburg",
jobs: [
{
"profession": "chef",
"salary": 1000
}, {
"profession": "gardener",
"salary": 800
}
]
},
{
name: "Sam",
surname: "Sonite",
jobs: [
{
"profession": "doctor",
"salary": 2000
}, {
"profession": "barber",
"salary": 850
}
]
}
I would like to find all the jobs that have a salary greater than 900, So that the result would be:
[
{
"profession": "chef",
"salary": 1000
}, {
"profession": "doctor",
"salary": 2000
}
]
I'm quite sure that I must resort to mongodb aggregation
. The best I managed to achieve is:
db.persons.aggregate([
{$unwind: "$jobs"},
{$match: {"jobs.salary": {$gt: 900}}},
{$project: {jobs: 1, _id: 0}}])
That returns:
[
{
"jobs": {
"profession": "chef",
"salary": 1000
}
},
{
"jobs": {
"profession": "doctor",
"salary": 2000
}
}
]
But this is not what I want. I want also the jobs
key to be removed.
I know one possibility is to specify each variable of the embedded document in the projection
like this:
db.persons.aggregate([
{$unwind: "$jobs"},
{$match: {"jobs.salary": {$gt: 900}}},
{$project:
{"profession": "$jobs.profession",
"salary": "$jobs.salary", _id: 0}}])
but I would prefer to avoid it, since the embedded documents could differ on some fields.