2017-08-28 3 views
0

文書のトップレベルに「タグ」フィールドを持たない以下のmongoコレクション「test」があります。

{ 
    "_id" : 1, 
    "title" : "123 Department Report", 
    "year" : 2014, 
    "subsections" : [ 
     { 
      "subtitle" : "Section 1: Overview", 
      "tags" : "SI", 
      "content" : "Section 1: This is the content of section 1." 
     }, 
     { 
      "subtitle" : "Section 2: Analysis", 
      "tags" : "STLW", 
      "content" : "Section 2: This is the content of section 2." 
     }, 
     { 
      "subtitle" : "Section 3: Budgeting", 
      "tags" : "TK", 
      "content" : { 
       "text" : "Section 3: This is the content of section3.", 
       "tags" : "HCS" 
      } 
     } 
    ] 
} 

私の要件は、「タグ」値「STLW」のみを持つサブセクションを選択することです。 次の集計クエリを実行しています。

私は以下の出力では、すべてのサブ文書を取得していますクエリを実行しているのが
db.test.aggregate([ 
    { $redact: { 
     $cond: {   
      if: { $or: [ {$ifNull: ['$tags', true]}, {$eq: [ "$tags" , 'STLW' ]} ] }, 
      then: "$$DESCEND", 
      else: "$$PRUNE" 
     } 
     } 
    } 
] 

{ 
    "_id" : 1, 
    "title" : "123 Department Report", 
    "year" : 2014, 
    "subsections" : [ 
     { 
      "subtitle" : "Section 1: Overview", 
      "tags" : "SI", 
      "content" : "Section 1: This is the content of section 1." 
     }, 
     { 
      "subtitle" : "Section 2: Analysis", 
      "tags" : "STLW", 
      "content" : "Section 2: This is the content of section 2." 
     }, 
     { 
      "subtitle" : "Section 3: Budgeting", 
      "tags" : "TK", 
      "content" : { 
       "text" : "Section 3: This is the content of section3.", 
       "tags" : "HCS" 
      } 
     } 
    ] 
} 

しかし、私は以下の出力をしたいです。

{ 
    "_id" : 1, 
    "title" : "123 Department Report", 
    "year" : 2014, 
    "subsections" : 
     { 
      "subtitle" : "Section 2: Analysis", 
      "tags" : "STLW", 
      "content" : "Section 2: This is the content of section 2." 
     } 
} 

これを達成するのに手伝ってもらえますか?

おかげ...........これはnecesarily redactオペレータを必要としません

+0

可能な複製(https://stackoverflow.com/questions [MongoDBを持つサブ文書の中で、配列をフィルタリングする方法]/15117030/how-to-filter-array-in-mongodb) – Veeram

答えて

0

、それはunwindmatch演算子を使用することによって達成することができます。次の呼び出し...

db.test.aggregate([ 

    // find documents which have at least one subsection having a tag with the value "STLW" 
    {$match: {'subsections.tags': 'STLW'}}, 

    // unwind subsections so that the intermediate ouput contains one 'quasi doc' for each subsection 
    {$unwind: '$subsections'}, 

    // filter out any of the 'quasi docs' which do not have a tag with the value "STLW" 
    {$match: {'subsections.tags': 'STLW'}} 
]) 

...この応答を生成します:

{ 
    "_id" : 1, 
    "title" : "123 Department Report", 
    "year" : 2014, 
    "subsections" : { 
     "subtitle" : "Section 2: Analysis", 
     "tags" : "STLW", 
     "content" : "Section 2: This is the content of section 2." 
    } 
} 
+0

はい私は知っています。しかし、私の場合、文書の膨大なサイズのためにCPUを集中的に使用することができます。したがって私はredactを試しています。もし処理する前に文書サイズを減らす方法があれば、それを試しています。 – Ravi

関連する問題