2017-03-17 1 views
0

몽고 쿼리가 붙어 있습니다. 나는 아주 큰 데이터이므로이 시간에 수정할 수없는 몽고 컬렉션 구조를 가지고 있습니다.Mongo Groupby 집계 "Key"가 아님

컬렉션에서 일부 결과를 수행해야하므로 모든 방법을 통해 그 결과를 얻으려고합니다. 여기

는 내 컬렉션의 JSON 스키마입니다 : -

{ 
    "date": "2017-01-01T00:00:00.000Z", 
    "bob":"P", 
    "jacob":"P", 
    "wilson":"A", 
    "dev":"SL" 
}, 
{ 
    "date": "2017-01-02T00:00:00.000Z", 
    "bob":"P", 
    "jacob":"A", 
    "wilson":"A", 
    "dev":"SL" 
}, 
{ 
    "date": "2017-01-03T00:00:00.000Z", 
    "bob":"P", 
    "jacob":"P", 
    "wilson":"A", 
    "dev":"SL" 
}, 
{ 
    "date": "2017-01-04T00:00:00.000Z", 
    "shashikant":"P", 
    "jacob":"P", 
    "wilson":"SL", 
    "dev":"SL" 
} 
.... 

출력으로 나는 구조의 아래 종류를 찾고 있어요 : -

from 1st jan 2017 to 30th jan 2017 

    bob  P  17 
    bob  A  2 
    wilson P  10 
    dev  SL. 1 
    ..... 

내 백엔드 루프백을 사용하고 있지만, 여전히 내가 사용할 수 있습니다 정상 mongodb 쿼리 출력을 얻을 수 있습니다.

도와주세요

답변

1

MongoDB는 배열에 대해서만 $ unwind를 허용합니다. 하지만 당신은 당신이 원하는 것을 달성하기 위해 간단한 mapReduce을 사용할 수

//Define the time frame here 
 
var from = new Date('2015-01-01T00:00:00.000Z'); 
 
var to = new Date('2025-01-01T00:00:00.000Z'); 
 

 
db.getCollection('test').mapReduce(function() { 
 
\t \t var keys = Object.keys(this); 
 

 
\t \t //If there is no date found on a record, simply skip 
 
\t \t if (!this.date) { 
 
\t \t \t return; 
 
\t \t } 
 

 
\t \t var date = new Date(this.date); 
 

 
\t \t //Skip the records that do not fit into [form; to] interval 
 
\t \t if (!(date >= from && date <= to)) { 
 
\t \t \t return; 
 
\t \t } 
 

 
\t \t for (var i = 0; i < keys.length; i++) { 
 
\t \t \t var key = keys[i]; 
 

 
\t \t \t //Emit each combination of key and value 
 
\t \t \t if (key !== 'date' && key !== '_id') { 
 
\t \t \t \t emit({key: key, value: this[key]}, {count: 1}); 
 
\t \t \t } 
 
\t \t } 
 
\t }, 
 

 
\t function (key, values) { 
 
\t \t var reduced = {count: 0}; 
 

 
\t \t for (var i = 0; i < values.length; i++) { 
 
\t \t \t var value = values[i]; 
 

 
\t \t \t //Simply counting the combinations here 
 
\t \t \t reduced.count += value.count; 
 
\t \t } 
 

 
\t \t return reduced; 
 
\t }, 
 
\t { 
 
\t \t //Passing the dates to mongo 
 
\t \t //so 'from' and 'to' will be avail in map, reduce and finalize 
 
\t \t scope: {from: from, to: to}, 
 
\t \t finalize: function (key, reducedValue) { 
 
\t \t \t //Changing the data structure just for a convenience 
 
\t \t \t return { 
 
\t \t \t \t propertyName: key.key, 
 
\t \t \t \t propertyValue: key.value, 
 
\t \t \t \t from: from, 
 
\t \t \t \t to: to, 
 
\t \t \t \t count: reducedValue.count 
 
\t \t \t }; 
 
\t \t }, 
 
\t \t out: {inline: 1} 
 
\t } 
 
);

내가 몽고 콘솔에서이 테스트를하지만,지도-감소도 몽고 출신 Node.js를로하고 몽구스 지원됩니다 잘.