$ cond>
$ projectの演算子 空のattrを置き換えるステージ nullのようなプレースホルダーを含む配列 これは、このドキュメントに attrが含まれていないことを示すマーカーとして使用できます。 要素。
したがって、追加の $ projectを挿入します $ unwindの直前にこのようなステージ :
{
$project: {
attrs: {$cond: {
if: {$eq: ['$attrs', [] ]},
then: [null],
else: '$attrs'
}}
}
},
唯一の注意点は、 nullになってしまうことです。 最終的なattrsの値 attrsのない少なくとも1つのドキュメントを含むグループの配列 要素なので、それらのクライアント側を無視する必要があります。
例
この例では、変更された $ matchを使用しています 例のステージは有効ではないためです。
入力ドキュメント
[
{_id: {type: 1, id: 2}, attrs: []},
{_id: {type: 2, id: 1}, attrs: []},
{_id: {type: 2, id: 2}, attrs: [{name: 'john', type: 22}, {name: 'bob', type: 44}]}
]
出力
{
"result" : [
{
"_id" : 1,
"attrs" : [
null
]
},
{
"_id" : 2,
"attrs" : [
{
"name" : "bob",
"type" : 44
},
{
"name" : "john",
"type" : 22
},
null
]
}
],
"ok" : 1
}
集約コマンド
db.test.aggregate([
{
$match: {
'_id.servicePath': {
$in: [
null
]
}
}
},
{
$project: {
_id: 1,
"attrs.name": 1,
"attrs.type": 1
}
},
{
$project: {
attrs: {$cond: {
if: {$eq: ['$attrs', [] ]},
then: [null],
else: '$attrs'
}}
}
},
{
$unwind: "$attrs"
},
{
$group: {
_id: "$_id.type",
attrs: {
$addToSet: "$attrs"
}
}
},
{
$sort: {
_id: 1
}
}
])