I am new to mongodb and I am struggling to understand something that I think should be pretty simple, maybe you can point me out in the right direction!
Lets say I have the following single document in a collection:
{
"id": "1234",
"name": "test",
"elements": [
{
"name": "element1",
"type": "exaple"
},
{
"name": "element2",
"type": "important"
},
{
"name": "element3",
"type": "exaple"
},
{
"name": "element4",
"type": "imporant"
},
{
"name": "element5",
"type": "exaple"
}
]
}
And I want to get the name of all the "elements" that are important for this document.
An example of doing the same using JQ:
cat test.json | jq '.elements[] | select(.type=="important").name'
"element2"
"element4"
I imagine I need to use some sort of aggregation but I am not being able to do this simple thing, any suggestion?
2
Answers
You can do this with a simple
$cond
in a$reduce
Mongo Playground
You can use an aggregation query like this:
$filter
to get only values you want (i.e. elements withimporant
type.$project
.Example here