2016-05-19 10 views
1

Gegeben das folgende Beispiel-Datensatz:Return Summe von Array-Elementen und anderen Bereichen

[ 
    { 
    _id: 1, 
    prices: [1,2,3], 
    category: 'stuff' 
    }, 
    { 
    _id: 2, 
    prices: [4,5,6], 
    category: 'stuff' 
    }, 
    { 
    _id: 3, 
    prices: [7,8,9], 
    category: 'misc' 
    } 
]; 

Wie kann ich wieder Daten erhalten, die wie folgt aussieht:

[ 
    { 
    _id: 1, 
    prices: 6, 
    category: 'stuff' 
    }, 
    { 
    _id: 2, 
    prices: 15, 
    category: 'stuff' 
    }, 
    { 
    _id: 3, 
    prices: 24, 
    category: 'misc' 
    } 
] 

Ich kann diese:

[ 
    { 
    _id: 1, 
    prices: 6 
    }, 
    { 
    _id: 2, 
    prices: 15 
    }, 
    { 
    _id: 3, 
    prices: 24 
    } 
] 

Mit etwas wie diesem:

[ 
    { $unwind: '$prices' }, 
    { $group: { _id: '$_id', prices: { $sum: '$prices' } } }, 
    { $project: { prices: 1 } } 
] 

Aber ich kann nicht herausfinden, wie man es bekommt, um "Kategorie" einzuschließen.

Antwort

1

Der optimale Weg, dies zu tun, ist MongoDB 3.2 oder neuer unter Verwendung des Akkumulatoroperators $sum in der Stufe $project.

db.collection.aggregate([ 
    { "$project": { 
     "price": { "$sum": "$prices" }, 
     "category": "$category" 
    }} 
]) 

, die produziert:

{ "_id" : 1, "category" : "stuff", "price" : 6 } 
{ "_id" : 2, "category" : "stuff", "price" : 15 } 
{ "_id" : 3, "category" : "misc", "price" : 24 } 

In MongoDB Version < = 3.0 benötigen Sie den $first Operator zu verwenden.

db.collection.aggregate([ 
    { $unwind: '$prices' }, 
    { $group: { 
     _id: '$_id', 
     prices: { $sum: '$prices' }, 
     category: { '$first': '$category' } 
    }} 
]) 
Verwandte Themen