2016-07-11 1 views
1

は、私は次のデータセットがあります。これまでのところ、私は集計クエリで遊ん

{ 
    "_id" : ObjectId("57684f2b61f2af6d49fa6dbd"), 
    "firstname" : "First1", 
    "surname" : "Sur1", 
    "email" : "[email protected]", 
    "goals" : [ 
    { 
     "gId" : "base1", 
     "count" : 2 
    }, 
    { 
     "gId" : "base2", 
     "count" : 1 
    } 
    ] 
} 

{ 
    "_id" : ObjectId("57684f2b61f2af6d49fa6dbd"), 
    "firstname" : "First1", 
    "surname" : "Sur1", 
    "email" : "[email protected]", 
    "goals" : [ 
    { 
     "gId" : "base1", 
     "recordDate" : ISODate("2016-06-21T20:05:48.972Z") 
    }, 
    { 
     "gId" : "base2", 
     "recordDate" : ISODate("2016-06-21T20:05:48.972Z") 

    }, 
    { 
     "gId" : "base1", 
     "recordDate" : ISODate("2016-06-21T20:05:48.972Z") 

    } 
] 
} 

を私は次の結果を必要とします私は私の問題の解決策を見つけることができませんでした。私のクエリはそれのように見えるが、それは動作しません。最初のビット$projectはそれ自身で正常に動作し、$unwind$groupも同様ですが、どのように組み合わせることができるのか分かりません。事前に

db.getCollection('users').aggregate(
{ 
    $project : { 
    firstname: "$firstname", 
    surname: "$surname", 
    email: "$email", 
    goals: "$goals" 
    } 
}, 
{ 
    $unwind: '$goals' 
}, 
{ 
    $group: { 
    gid: '$goals.gId', 
    count: {'$sum': 1} 
    } 
} 
) 

おかげで、 トム

答えて

1

db.getCollection('users').aggregate(
    { 
     $unwind: '$goals' 
    }, 
    { 
     $group: { 
     _id: { 
      firstname: "$firstname", 
      surname: "$surname", 
      email: "$email", 
      gId: "$goals.gId" 
     }, 
     count: {'$sum': 1} 
     } 
    }, 
    { 
     $group: { 
      _id: { 
       firstname: "$_id.firstname", 
       surname: "$_id.surname", 
       email: "$_id.email" 
      }, 
      goals: { 
       $push: { 
        gId: "$_id.gId", 
        count: "$count" 
       } 
      }   
     } 
    }, 
    { 
     $project: { 
      _id: 0, 
      firstname: "$_id.firstname", 
      surname: "$_id.surname", 
      email: "$_id.email", 
      goals: 1 
     } 
    } 
) 

結果はWOWこの

{ 
    "goals" : [ 
     { 
      "gId" : "base2", 
      "count" : 1.0 
     }, 
     { 
      "gId" : "base1", 
      "count" : 2.0 
     } 
    ], 
    "firstname" : "First1", 
    "surname" : "Sur1", 
    "email" : "[email protected]" 
} 
+0

のように見え、次のパイプラインでそれを試してみてください。あなたはどうやってそのような質問を思いついたのですか?それはかなり近いです: "ゴール":[ { "カウント":2.0 }、 { "カウント":1.0 } ]、 "ファーストネーム": "First1"、 "姓":「SUR1 」、 "電子メール": "[email protected]" }しかし、私はあまりにも{ のような目標の記述を必要とする "カウント":1.0、GID: "BASE2" } –

+0

"BASE2"、 "BASE1"実際には配列の要素に含まれています。再度確認してください – DAXaholic

関連する問題