2017-11-12 6 views
0

私はこのクエリは、私がdebitoの集計値を必要とする集計で助けを必要とは私が配列内の集計にMongoDBを使用する必要がある

{ 
"_id" : ObjectId("5a088f6584ccb0a665900726"), 
"usuario" : "tamura", 
"creditos" : [ 
    { 
     "nome_do_credito" : "credito inicial", 
     "credito" : 0 
    } 
], 
"debitos" : [ 
    { 
     "nome_do_debito" : "debito inicial", 
     "debito" : 0 
    }, 
    { 
     "nome_do_debito" : "Faculdade", 
     "debito" : "150.00" 
    } 
] 

}

私は出力を必要とする

デビット:150

(0 + 150)

答えて

0

文字列で数値演算を行うことができないため、最初にdebitoフィールドを数値タイプ(150.00など)に変換する必要があります("150.00"など)。そして、次のクエリは、トリックを行う必要があります。

場合
db.collection.aggregate({ 
    $project: { 
     "debitos": { 
      $sum: "$debitos.debito" 
     } 
    } 
}) 

あなたのコレクションに複数の文書があり、総合計は、すべての文書の上にあなたがこれを実行することができますしたい:

db.collection.aggregate({ 
    $unwind: "$debitos" // flatten the "debitos" array 
}, { 
    $group: { 
     "_id": null, // do not really group, just throw all documents in the same group 
     "debitos": { 
      $sum: "$debitos.debito" // sum up all debito fields 
     } 
    } 
}) 
+0

をuに感謝、私は私のnodejs mongodb heheでparseIntを忘れる –

関連する問題