mongodb聚合嵌入式文档值

Tom*_*mmy 9 mongodb mongodb-query

我在mongodb中使用了一些聚合函数.

说我有这样的文件

 [
 {
    _id: "1",
    periods: [
      {
         _id: "12",
         tables: [
           {
              _id: "121",
              rows: [
                  { _id: "1211", text: "some text"},
                  { _id: "1212", text: "some other text"},
                  { _id: "1213", text: "yet another text"},

              ]
           }
         ]
      },
      {
         _id: "13",
         tables: [
           {
              _id: "131",
              rows: [
                  { _id: "1311", text: "different text"},
                  { _id: "1312", text: "Oh yeah"}                      
              ]
           }
         ]
      }
    ]
 },
 {
    _id: "2",
    periods: [
      {
         _id: "21",
         tables: [
           {
              _id: "212",
              rows: [
                  { _id: "2121", text: "period2 text"},
                  { _id: "2122", text: "period2 other text"},
                  { _id: "2123", text: "period2 yet another text"},

              ]
           }
         ]
      }
    ]
 }
 ]
Run Code Online (Sandbox Code Playgroud)

现在我想使用mongodb查询来检索一个特定顶级项目的所有唯一文本.

例如,聚合顶部_id的所有文本1.这意味着我想要获得两个期间子树中的所有文本.

预期产量如下:

在_id上过滤聚合文本:1

[
   "some text",
   "some other text",
   "yet another text",
   "different text",
   "Oh yeah"
]
Run Code Online (Sandbox Code Playgroud)

在_id上过滤聚合文本:2

[
  "period2 some text",
  "period2 some other text",
  "period2 yet another text"
]
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经设法聚合所有文本,但最终在多个数组中,我没有设法使用$ match过滤它们的id,

我当前的聚合查询看起来像这样

[ 
    { "$project" : { "text" : "$periods.tables.rows.text" , "_id" : "$_id"}},
    { "$unwind" : "$text"},
    { "$group" : { "_id" : "$_id" , "texts" : { "$addToSet" : "$text"}}},
    { "$project" : { "_id" : 0 , "texts" : 1}} 
]
Run Code Online (Sandbox Code Playgroud)

它给了我一个像这样的结果

{ "texts" : [ 
        [ [ "Some text" , "Some other text" , "yet another text"] , [ "different text" , "oh yeah" ] ],
        [ [ "period2 some text", "period2 some other text", "period2 yet another text"]]
    ]}
Run Code Online (Sandbox Code Playgroud)

如果我添加$ match:{_ id:1},则不会返回任何结果.

任何人都可以帮我解决这个问题,或者指出我如何解决它.我一直在寻找资源,但似乎没有找到关于如何使用这些聚合函数的任何好的文档.mongodb文档只使用简单的文档.

PS我知道我可以使用mapreduce做到这一点,但希望能够使用聚合函数.

att*_*ish 16

Unwind only goes down one level, so you have to call as many times as many levels you have if you do it like

[ 
    { "$project" : { "text" : "$periods.tables.rows.text" , "_id" : "$_id"}},
    { "$unwind" : "$text"},
    { "$unwind" : "$text"},
    { "$unwind" : "$text"},
    { "$group" : { "_id" : "$_id" , "texts" : { "$addToSet" : "$text"}}},
    { "$project" : { "_id" : 0 , "texts" : 1}} 
]
Run Code Online (Sandbox Code Playgroud)

It will work as you expect.