9

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"},

              ]
           }
         ]
      }
    ]
 }
 ]

ここで、mongodb クエリを使用して、1 つの特定の最上位アイテムの一意のテキストをすべて取得したいと考えています。

たとえば、top _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 を使用してこれを実行できることはわかっていますが、これに集計関数を使用できることを望んでいました。

4

1 に答える 1

18

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}} 
]

期待どおりに動作します。

于 2013-09-13T14:32:36.260 に答える