2017-08-28 9 views
0

我有一个下面的mongo集合“test”,它没有在文档的顶层有“tags”字段。

{ 
    "_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." 
     } 
} 

任何人都可以帮助我实现这个目标吗?

感谢...........

+0

的可能的复制(https://stackoverflow.com/questions [如何与MongoDB的子文档滤波器阵列]/15117030/how-to-filter-array-in-subdocument-with-mongodb) – Veeram

回答

0

这并不necesarily需要redact运营商,它可以通过使用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密集操作的放松是有效的。因此我正在尝试使用编辑器,如果某些情况下我们可以在处理之前减少文档大小。 – Ravi