2016-09-24 6 views
0

Ich habe zwei verschiedene Mungo Sammlung wie folgt:MongoDB-Lookup + Gruppe mit Mungo

{ "_id" : 1, "countryId" : 1, "price" : 12, "quantity" : 24 } 
{ "_id" : 2, "countryId" : 2, "price" : 20, "quantity" : 1 } 
{ "_id" : 3 } 
{ "_id" : 4, "countryId" : 1, "price" : 12, "quantity" : 24 } 



{ "_id" : 1, "id" : 1, description: "Colombia"} 
{ "_id" : 3, "id" : 2, description: "Mexic" } 

Ich versuche, sie zu aggregieren, so dass ich ein Ergebnis wie folgt haben:

{"country":"Colombia","total":48} 
{"country":"Mexic","total":1} 

Ich habe viele Dinge ausprobiert, aber es ist immer versagt hier ist die letzte Version von dem, woran ich arbeite (ich habe die Daten geändert, aber Sie bekommen die Idee):

Model.aggregate([ 
     { 
     $lookup: 
     { 
      from: "countryList", 
      localField: "countryId", 
      foreignField: "id", 
      as: "country" 
     }, 
     { 
     $project: { 
        quantity:1, country:{$country:"$countryList.description"} 
       } 
     },{ 
     $group:{ 
       { _id : null, qtyCountry: { $sum: "$quantity" } } 
     } 
     } 
    }],function (err, result) { 
     if (err) { 
      console.log(err); 
     } else { 
      console.log(result) 
     } 
    } 
); 

Ist es überhaupt möglich?

Antwort

2

Ja, es ist möglich. Sie können die folgende Aggregationspipeline versuchen.

var pipeline = [ 
        {"$match":{"countryId":{"$exists":true}}}, 
        {"$group" : {"_id":"$countryId", "quantity":{"$sum":"$quantity"}}}, 
        {"$lookup":{"from":"countryList","localField":"_id", "foreignField":"id","as":"country"}}, 
        {"$unwind":"$country"}, 
        {"$project": {"country":"$country.description", "total":"$quantity", _id:0}} 
       ] 

Beispielausgabe:

{ "country" : "Mexic", "total" : 1 } 
{ "country" : "Colombia", "total" : 48 } 
+0

es bis Lookup funktioniert, dann ist das Abroll Ergebnis in einem leeren Array; /, wenn ich entferne entspannen i get { "Land": [], "total": 4234}, {"country": [], "total": 43} –

+0

@ Cam.phiefr hat meine Antwort aktualisiert ... Die Lookup-Sammlung von Land zu Land geändertList – 4J41

+1

Danke, funktioniert perfekt !. –