2016-07-28 2 views
0

필드 계산하는 방법 :이 해당 그룹의 문서MongoDB를 나는이 같은 일부 데이터가

{ 
    user_id:1, 
    group_id:123, 
    discription:null 
}, 
{ 
    user_id:1, 
    group_id:321, 
    discription:null 
}, 
{ 
    user_id:1, 
    group_id:123, 
    discription:"text" 
}, 
{ 
    user_id:1, 
    group_id:321, 
    discription:"another text" 
}, 
{ 
    user_id:1, 
    group_id:321, 
    discription:"another another text" 
}, 
etc.. 

내가 각 그룹에서 모든 그룹 (그룹 GROUP_ID에 의해) 문서의 수를 얻기 원하고, 카운트를 " discription "을 Null 값과 Null 값과 함께 사용하지 마십시오. 그래서 나는 같은 결과가 필요합니다

[ 
    [group_id:123, count:2, isNull:1, isNotNull:1], 
    [group_id:321, count:3, isNull:1, isNotNull:2] 
] 

내가 어떻게 그룹 필드 "GROUP_ID"로 알고하고 "수"를 얻을,하지만 나는 "설명"에 대한 정보를 얻을하는 방법을 모르겠어요.

db.collection.aggregate([ 
    { 
     $match:{ 
      user_id:1 
     } 
    }, 
    { 
     $group:{ 
      _id:'$group_id', 
      group_id:{$first:'$group_id'}, 
      count:{'$sum':1} 
     } 
    } 
]) 

답변

0

이 쿼리

db.testing.aggregate([{ 
     $match:{ 
      user_id:1 
     } 
    },  
    {$project:{_id:0,user_id:1,group_id: 1,description: { $ifNull: [ "$discription", 1 ] }}}, 
    { 
     $group:{ 
      _id:'$group_id',    
      group_count:{'$sum':1}, 
      IsNull:{"$sum":"$description"} 
     } 
    }, 
    {$project:{_id:0,group_id:"$_id", count:"$group_count", isNull:"$IsNull", isNotNull:{ $subtract:["$group_count","$IsNull"]}}} 
]) 
을 확인하시기 바랍니다
관련 문제