2013-08-16 6 views
0

내가 colletions 내가MongoDB를 GROUPBY 쿼리

[ 
{"tid" : "1","me" : 3,"you": 2}, 
{"tid" : "2","me" : 2,"you": 3} 
] 

아래 내가 그룹을 시도 같은 결과를 원하는 한

{ "type" : "me", "tid" : "1" } 
{ "type" : "me", "tid" : "1" } 
{ "type" : "me", "tid" : "1" } 
{ "type" : "you", "tid" : "1" } 
{ "type" : "you", "tid" : "1" } 

{ "type" : "me", "tid" : "2" } 
{ "type" : "me", "tid" : "2"} 
{ "type" : "you", "tid" : "2"} 
{ "type" : "you", "tid" : "2" } 
{ "type" : "you", "tid" : "2"} 

같은 기록을 포함해야; 집계 쿼리는 필요한 결과 형식을 가져 오지 않습니다.

다음은 그룹 쿼리입니다. 다음

[ 
    {"tid" : "1", "type" : "me" ,"total": 3 }, 
    {"tid" : "1","type" : "you" ,"total": 2 }, 
    {"tid" : "2", "type" : "me" ,"total": 2 }, 
    {"tid" : "2","type" : "you" ,"total": 3 } 
] 

집계 쿼리

db.coll.aggregate([ 
    {$match : { "tid" : {"$in" : ["1","2"]}}}, 
    {$group : { _id : {tid : "$tid",type : "$type"},total : {"$sum" : 1}}} 
]) 

가 나는 결과를 지정 또는 내가 가지고 얻을 수있다

{ 
    "result" : 
    [ 
    {"_id" : {"tid" : "1","type" : "me"},"total" : 3}, 
    {"_id" : {"tid" : "2","type" : "me" },"total" : 2}, 
    {"_id" : {"tid" : "2","type" : "you"},"total" : 3} 
    ] 
    "ok" : 1 
} 

결과 다음과 같은 준다처럼

db.coll.group({ 
    key: {tid : 1,type:1}, 
    cond: { tid : { "$in" : [ "1","2"]} }, 
    reduce: function (curr,result) { 
    result.total = result.total + 1 
    }, 
    initial: { total : 0} 
}) 

그것의 결과는 약간의 조작을하는 것 이온 코드.

덕분에 당신이 당신의 집계를 변경하는 경우

답변

1

:

db.so.aggregate([ 
    { $match : { "tid" : { "$in" : ["1", "2"] } } }, 

    { $group : { 
     _id : { tid : "$tid", type : "$type" }, 
     total : { "$sum" : 1 } 
    } }, 

    { $group : { 
     _id : "$_id.tid", 
     values: { $push: { type: "$_id.type", total: '$total' } } 
    } } 
]) 

이 그런 다음 출력은 다음과 같습니다

{ 
    "result" : [ 
     { 
      "_id" : "1", 
      "values" : [ 
       { "type" : "you", "total" : 2 }, 
       { "type" : "me", "total" : 3 } 
      ] 
     }, 
     { 
      "_id" : "2", 
      "values" : [ 
       { "type" : "me", "total" : 2 }, 
       { "type" : "you", "total" : 3 } 
      ] 
     } 
    ], 
    "ok" : 1 
} 

즉 당신이 원하는 것과 동일하지 않지만, 그것은 것입니다 당신이 얻을 수있는 가장 가까운 것. 그리고 귀하의 응용 프로그램에서, 당신은 쉽게 처럼과 같은 값을 꺼낼 수 있습니다.

그냥 일반적으로 당신이 에 값 ( you, me)을 촉진 할 수 있음을 염두에 두어야 - 키가 제한된 (3-4 항목 최대)의 경우를 제외하고.

+0

감사합니다. @derick .. –