Data:
db={
"Test": [
{
"x": "a"
},
{
"x": "a",
"y": 1
},
{
"x": "a",
"y": 2
}
]
}
When aggregating like this:
db.Test.aggregate([
{
"$group": {
"_id": {
"x": "$x"
},
"y": {
"$addToSet": "$y"
}
}
}
])
... I expectedly get this:
[
{
"_id": {
"x": "a"
},
"y": [
2,
1
]
}
]
But I want to group those x
s separately where y
is null and get this result:
[
{
"_id": {
"x": "a"
},
"y": []
},
{
"_id": {
"x": "a"
},
"y": [
1,
2
]
}
]
Is this possible?
db.Test.aggregate([
{
"$group": {
"_id": {
"x": "$x",
"z": {
$cond: [
{$ifNull: ["$y", false]},
true,
false
]
}
},
"y": {
"$addToSet": "$y"
}
}
}
])