{
"_id": 1,
"title": {
header1:{ "name":"A" , age:10, "active":true},
header2:{ "name":"B" , age:15, "active":false},
header3:{ "name":"C" , age:20, "active":true},
header4:{ "name":"D" , age:30, "active":true},
header5:{ "name":"E" , age:35, "active":false},
header6:{ "name":"F" , age:40, "active":true},
header7:{ "name":"G" , age:45, "active":false},
}
}
How can I show only those headers whose active value is false?
CodePudding user response:
$project
1.1 Convert key-value pair to array via
$objectToArray
forheaders
field . 1.2$filter
with$$this.v.active
which isfalse
.$project
2.1 Convert
headers
to key-value pair via$arrayToObject
and assign totitle
field.
db.collection.aggregate([
{
$project: {
_id: 1,
headers: {
$filter: {
"input": {
$objectToArray: "$title"
},
"cond": {
"$eq": [
"$$this.v.active",
false
]
}
}
}
}
},
{
$project: {
_id: 1,
title: {
"$arrayToObject": "$headers"
}
}
}
])