mongodb汇总嵌入式文档值

汤米

我在mongodb中使用某些聚合功能进行Strugling。

说我有一些像这样的文件

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

              ]
           }
         ]
      }
    ]
 }
 ]

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

例如,汇总顶部_id 1的所有文本。这意味着我要获取两个期间子树中的所有文本。

预期输出如下:

聚合对_id进行过滤的文本:1

[
   "some text",
   "some other text",
   "yet another text",
   "different text",
   "Oh yeah"
]

聚合对_id进行过滤的文本:2

[
  "period2 some text",
  "period2 some other text",
  "period2 yet another text"
]

到目前为止,我已经设法汇总了所有文本,但是最终以多个数组的形式出现,并且我还没有使用$ match在id上对它们进行过滤,

我当前的汇总查询如下所示

[ 
    { "$project" : { "text" : "$periods.tables.rows.text" , "_id" : "$_id"}},
    { "$unwind" : "$text"},
    { "$group" : { "_id" : "$_id" , "texts" : { "$addToSet" : "$text"}}},
    { "$project" : { "_id" : 0 , "texts" : 1}} 
]

它给了我一个类似这样的结果

{ "texts" : [ 
        [ [ "Some text" , "Some other text" , "yet another text"] , [ "different text" , "oh yeah" ] ],
        [ [ "period2 some text", "period2 some other text", "period2 yet another text"]]
    ]}

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

任何人都可以帮我解决这个问题,或为我指出解决方法的方向。我一直在寻找资源,但是似乎找不到关于如何使用这些聚合函数的任何好的文档。mongodb文档仅使用简单的文档。

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

t

展开只会下降一级,因此您必须像执行此操作一样调用多次

[ 
    { "$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}} 
]

它会按您期望的那样工作。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章