2016-07-06 3 views
1

에서 중복 키가 그룹과 하나의 문서를 얻을 수 있습니다 user_id이지만 다른 경우 register_time 일 경우 user_id이 동일한 경우 어떻게 하나의 레코드 만 가져올 수 있습니까?방법은 다음과 같이 나는 총을 가지고 MongoDB를

{ "_id" : { "country_code" : "US", "user_id" : "d2a0fe91", "os" : "Android", "channel" : "000001", "register_time" : ISODate("2016-06-30T22:47:43Z") }, "count" : 1 }  
{ "_id" : { "country_code" : "US", "user_id" : "77911591", "os" : "Android", "channel" : "000001", "register_time" : ISODate("2016-06-30T19:47:21Z") }, "count" : 1 } 
{ "_id" : { "country_code" : "IN", "user_id" : "1b72fd12", "os" : "Android", "channel" : "000001", "register_time" : ISODate("2016-06-30T19:17:28Z") }, "count" : 1 } 
{ "_id" : { "country_code" : "IN", "user_id" : "1b72fd12", "os" : "Android", "channel" : "000001", "register_time" : ISODate("2016-06-30T19:15:13Z") }, "count" : 1 } 
{ "_id" : { "country_code" : "ID", "user_id" : "045f1637", "os" : "Android", "channel" : "000001", "register_time" : ISODate("2016-06-30T19:02:19Z") }, "count" : 1 } 

답변

1

는 문서가 동일한 사용자하지만 서로 다른 register_time 여러 문서가있을 때 어떻게 보일지 언급하지 않았다 같은 몇 가지 솔루션이 있습니다.
다음은 마지막 $group 단계를 변경하여 $push의 값을 가진 register_time 값의 배열을 유지하거나, 필요하다면 - $first으로 유지합니다. register_time으로 파이프 라인을 정렬 할 때 $first/$last을 사용하여 사용자 당 첫 번째/마지막 register_time을 원하는 결과로 유지할 수 있습니다.

"$group" : { 
     "_id" : { 
      "country_code" : "$country_code", 
      "user_id" : "$user_id", 
      "os" : "$os", 
      "channel" : "$channel", 
     }, 
     "register_times" : { 
      $push: "$register_time" 
     }, 
     "any_register_time" : { 
      $first: "$register_time" 
     },     
     "count" : { 
      "$sum" : 1 
     } 
} 
+0

감사합니다.하지만 더 많은 질문이있을 수 있습니다. 1/7/2016-4/7/2016에서 선택하면 user_id가 나타나기 전에 나타나는지 확인할 수 있습니다. 나는 1/7에서 4/7에 기록을 보여주지 않을 것이다. –

관련 문제