2016-01-11 9 views
5

Załóżmy kolekcję o schemacie jak jak pokazano poniżej:Jak mogę zdobyć górne n segmentów dla agregacji i wszystkich innych segmentów połączonych w "inne" wiadro?

{ 
    "customer" : <unique-id-for-customer>, 
    "purchase" : <number>, 
} 

Teraz chcę, aby uzyskać top 5 klientów (poprzez zakup-queantity) i 6. wiadro jest „inne”, która łączy w sobie wszystkie ilości zakupu od innych klientów.

Zasadniczo wyjście agregacji powinna być jak:

{ "_id" : "customer100", "purchasequantity" : 4000000 } 
{ "_id" : "customer5", "purchasequantity" : 81800 } 
{ "_id" : "customer4", "purchasequantity" : 40900 } 
{ "_id" : "customer3", "purchasequantity" : 440 } 
{ "_id" : "customer1", "purchasequantity" : 300 } 
{"_id" : "others", "purchasequantity" : 29999} 
+0

myślę, że to nie jest możliwe za pomocą jednego polecenia agregacji. – dikesh

+2

Ja też próbowałem wszystkiego, co mogłem .. nie mogłem wymyślić sposobu na odzyskanie wyników w jednym poleceniu. db.aggregations.aggregate ([{$ sort: {purchasequantity: -1}}, {$ limit: 5}]); i db.aggregations.aggregate ([{$ sort: {purchasequantity: -1}}, {$ skip: 5}, {$ group: {_ id: "others", totalAmount: {$ sum: '$ buyquantity'}} }]); wyniki muszą zostać połączone. – harshavmb

+0

Pierwszy Aggregation: db.test.aggregate ([ \t { \t \t "$ sort": { "zakup": -1} \t} \t { \t \t "$ projekt": { \t \t \t _id: '$ klienta, \t \t \t 'zakup': 1 \t \t} \t} \t { \t \t $ granica: 5 \t} ]) drugiej Agregacja: db.test.aggregate ([ \t { \t \t "$ sortowania" { "zakupu" -1} \t} \t { \t \t $ pominąć: 5 \t}, \t { \t \t "$ grupę": { \t \t \t _id: 'pozostałe' \t \t \t 'zakup': {$ suma: "$ zakup"} \t \t} \t} ]) – dikesh

Odpowiedz

1

Co chcesz nazywa weighting. Aby to zrobić, musisz dodać wagę do swoich dokumentów przez $project, używając ich i używając operatora $cond, a następnie posortuj je według "waga" w rosnącej liczbie innych i według "kupnaquantity" w porządku malejącym.

db.collection.aggregate([ 
    { "$project": { 
     "purchasequantity": 1, 
     "w": { 
      "$cond": [ { "$eq": [ "$_id", "others" ] }, 1, 0 ] 
     } 
    }}, 
    { "$sort": { "w": 1, "purchasequantity": -1 } } 
]) 

Które zwraca:

{ "_id" : "customer100", "purchasequantity" : 4000000, "w" : 0 } 
{ "_id" : "customer5", "purchasequantity" : 81800, "w" : 0 } 
{ "_id" : "customer4", "purchasequantity" : 40900, "w" : 0 } 
{ "_id" : "customer3", "purchasequantity" : 440, "w" : 0 } 
{ "_id" : "customer1", "purchasequantity" : 300, "w" : 0 } 
{ "_id" : "others", "purchasequantity" : 29999, "w" : 1 } 
Powiązane problemy