午後すべてMongoDB集約クエリによって生成された配列を反復する
MongoDB 3.4で集約クエリを処理するのは本当に苦労しています。
categories
var categories = [];
database.collection("item").aggregate([{
$group : {
_id : "$category",
num : {$sum : 1}
}},
{$sort:{_id:1}}]).toArray(function(err, data){
categories.push(...data);
callback(categories);
console.log(categories);
})
}
は次のようになります:
私はこのコードを使用して首尾よく行うことができました
categories
と呼ばれる空の配列に私の集計クエリの結果を押す行うために私を求めている問題を抱えています
:In addition to the categories created by your aggregation query, include a document for category "All" in the array of categories passed to the callback. The "All" category should contain the total number of items across all categories as its value for "num". The most efficient way to calculate this value is to iterate through the array of categories produced by your aggregation query, summing counts of items in each category.
[ { _id: 'Apparel', num: 6 },
{ _id: 'Books', num: 3 },
{ _id: 'Electronics', num: 3 },
{ _id: 'Kitchen', num: 3 },
{ _id: 'Office', num: 2 },
{ _id: 'Stickers', num: 2 },
{ _id: 'Swag', num: 2 },
{ _id: 'Umbrellas', num: 2 } ]
次は、私は、次のタスクを持っています0
問題は、.toArray()
メソッドdata
のパラメータが配列のように動作することがあり、時にはそうでないように見えるということです。たとえば、num
キーの値をcategories
の配列に追加する場合は、categories.push(...data["num"])
と入力してください。undefined is not iterable
というエラーが表示されます。
私は各data.num
キーを反復処理できないので、値を抽出してそれを実行中のすべてのdata.num
値に加算することはできません。
ここで何が起こっているのか理解できません。
あなたのソリューションは私が探していたものに近く、あなたの応答に感謝します。私はあなたの入力後に全体的に私が扱っていることをよりよく理解していると思います。私が明確にしていなかったのは、新しい '{category:" All} '文書を' data'配列の一部にする必要があったことです。私はあなたの下に自分の答えを掲載します。 – m00saca