2016-08-31 3 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의 수만 반환하도록 할 수 있습니까? 영국에서 xported? 또한 출력을 풀지 않고도 더 좋은 결과를 얻을 수있는 방법이 있습니까?

답변

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"}} 
);