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? 또한 출력을 풀지 않고도 더 좋은 결과를 얻을 수있는 방법이 있습니까?