2016-08-31 6 views
0

私はモンゴデータベースに以下の書類を持っている:MongoDBの埋め込まれた文書 - 集計クエリ

db.totaldemands.insert({ "data" : "UKToChina", "demandPerCountry" : 
{ "from" : "UK" , to: "China" , 
    "demandPerItem" : [ { "item" : "apples" , "demand" : 200 }, 
    { "item" : "plums" , "demand" : 100 } 
] } }); 

db.totaldemands.insert({ "data" : "UKToSingapore", 
"demandPerCountry" : { "from" : "UK" , to: "Singapore" , 
"demandPerItem" : [ { "item" : "apples" , "demand" : 100 }, 
    { "item" : "plums" , "demand" : 50 } 
] } }); 

私はどの国に英国からエクスポートりんごの数を見つけるためのクエリを記述する必要があります。

私は次のクエリ試してみました:

db.totaldemands.aggregate(
{ $match : { "demandPerCountry.from" : "UK" , 
    "demandPerCountry.demandPerItem.item" : "apples" } }, 
    { $unwind : "$demandPerCountry.demandPerItem" }, 
    { $group : { "_id" : "$demandPerCountry.demandPerItem.item", 
    "total" : { $sum : "$demandPerCountry.demandPerItem.demand" 
    } } } 
); 

をしかし、それは私に以下のように両方のリンゴやプラムで出力できます:

{ "_id" : "apples", "total" : 300 } 
{ "_id" : "plums", "total" : 150 } 

しかし、私の予想される出力は次のとおりです。

{ "_id" : "apples", "total" : 300 } 

このように、リンゴの数eを返すように上記のクエリを変更するにはどうすればよいですか英国出身ですか? また、巻き戻さずに出力を得るための他の方法がありますか?

答えて

1

$ matchを追加して、りんごだけを取得することができます。

文書構造を組み込み、集計を行っているので、ここでは$ unwindが必要です。代わりのオプションは、マップして減らすことができます。ただし、ここでは巻き戻しが最も適しています。

パフォーマンスを考えている場合は、パフォーマンスを向上させるために巻き戻してください。

db.totaldemands.aggregate(
{ $match : { "demandPerCountry.from" : "UK" , 
    "demandPerCountry.demandPerItem.item" : "apples" } }, 
    { $unwind : "$demandPerCountry.demandPerItem" }, 
    { $group : { "_id" : "$demandPerCountry.demandPerItem.item", 
    "total" : { $sum : "$demandPerCountry.demandPerItem.demand" 
    } } }, 
    {$match : {"_id" : "apples"}} 
); 
関連する問題