2017-09-08 2 views
0

Zum Beispiel habe ich eine Sammlung:MongoDB Gruppe mit Art und Grenze für jede Gruppe

{ "_id" : 1, "name" : "abc", "score" : 10 } 
{ "_id" : 2, "name" : "abc", "score" : 15 } 
{ "_id" : 3, "name" : "abc", "score" : 20 } 
{ "_id" : 4, "name" : "xyz", "score" : 10 } 
{ "_id" : 5, "name" : "xyz", "score" : 15 } 
{ "_id" : 6, "name" : "xyz", "score" : 20 } 

Wie kann ich eine Abfrage in MongoDB zu einer Gruppe tun, indem name dann sortiert nach score und nehmen Sie es mit limit=2. Ich möchte wie folgt erhalten:

{"_id": "abc", "items": [ 
      { "_id" : 3, "name" : "abc", "score" : 20 }, 
      { "_id" : 2, "name" : "abc", "score" : 15 }] 
    } 
    {"_id": "xyz", "items": [ 
      { "_id" : 6, "name" : "xyz", "score" : 20 }, 
      { "_id" : 5, "name" : "xyz", "score" : 15 }] 
    } 

Antwort

0

Meine Lösung ist

db.collection.aggregate([ 
    {$sort:{name:-1, score:-1}}, 
    {$group:{_id:"$name",items:{$push:{score:"$score"}}}}, 
    {$project:{items:{$slice:["$items", 2]}}}]) 
.pretty() 

kehrt

{ 
    "_id" : "abc", 
    "items" : [ 
     { 
      "score" : 20 
     }, 
     { 
      "score" : 15 
     } 
    ] 
} 
{ 
    "_id" : "xyz", 
    "items" : [ 
     { 
      "score" : 20 
     }, 
     { 
      "score" : 15 
     } 
    ] 
} 
0

Versuchen Sie dies.

unwind = { "$unwind" : "$score" }; 

    sort = { "$sort" : { "score" : -1 } }; 

    group = { 
     "$group" : { 
      "_id" : "$name", 
      "scores" : { 
       "$push" : { 
        "_id": "$_id", 
        "score": "$score", 
        "name": "$name" 
       } 
      } 
     } 
    } 

    project = { 
    "$project" : { 
     "_id" : "$_id", 
     "items" : { 
      "$slice" : ["$scores",0,2] 
     } 
    } 
    } 

db.collection.aggregate([unwind,sort,group,project]).pretty() 
+0

Haben Sie das versucht? –