0

私は、単一のアレイ構造にすべてのアクティブなカテゴリを選択します。このことから春データのMongoDB階層

[ 
    { 
     "categoryId": 1, 
     "categoryName": "Category 1", 
     "childCategory": null, 
     "active": false 
    }, 
    { 
     "categoryId": 2, 
     "categoryName": "Category 2", 
     "active": true, 
     "childCategory": [ 
      { 
       "categoryId": 4, 
       "categoryName": "Category 4", 
       "childCategory": null, 
       "active": false 
      }, 
      { 
       "categoryId": 5, 
       "categoryName": "Category 5", 
       "childCategory": null, 
       "active": true 
      } 
     ] 
    }, 
    { 
     "categoryId": 10, 
     "categoryName": "Category 10", 
     "childCategory": null, 
     "active": true 
    } 
] 

の下に定義されたように私は、階層構造内のネストされたJSONオブジェクトを持っています。私の出力は

[ 
    { 
     "categoryId": 2, 
     "categoryName": "Category 2", 
     "active": true 
    }, 
    { 
     "categoryId": 5, 
     "categoryName": "Category 5", 
     "active": true 
    }, 
    { 
     "categoryId": 10, 
     "categoryName": "Category 10", 
     "active": true 
    } 
] 

です。このデータを1つのクエリステートメントで直接取得することは可能ですか?私はmongodbのために春のデータを使用しています。

答えて

1

以下の集計を試すことができます。

$redact一度に文書レベルを通過し、一致基準で$$DESCEND$$PRUNEを実行する必要があります。

$unwind$childCategorypreserveNullAndEmptyArraysnullの値を保持する。

db.collection.aggregate({ 
    $redact: { 
     $cond: [{ 
      $eq: ["$active", true] 
     }, "$$DESCEND", "$$PRUNE"] 
    } 
}, { 
    $unwind: { 
     path: "$childCategory", 
     preserveNullAndEmptyArrays: true 
    } 
})